Dereference a structure to get value of first member

1.8k views Asked by At

I found out that address of first element of structure is same as the address of structure. But dereferencing address of structure doesn't return me value of first data member. However dereferencing address of first data member does return it's value. eg. Address of structure=100, address of first element of structure is also 100. Now dereferencing should work in the same way on both.

Code:

#include <iostream>
#include <cstring>

struct things{
    int good;
    int bad;
};

int main()
{
    things *ptr = new things;
    ptr->bad = 3;
    ptr->good = 7;
    std::cout << *(&(ptr->good)) <<" " << &(ptr->good) << std::endl;
    std::cout << "ptr also print same address = " << ptr << std::endl;
    std::cout << "But *ptr does not print 7 and gives compile time error. Why ?" << *ptr << std::endl;
    return 0;
}
4

There are 4 answers

6
Fernando Pérez On

You can do a cast of the pointer to Struct, to a pointer to the first element of the struct so the compiler knows what size and alignment to use to collect the value from memory. If you want a "clean" cast, you can consider converting it to "VOID pointer" first.
_ (Struct*) to (VOID*) to (FirstElem*) _
Also see: Pointers in Stackoverflow
Hope it helps!!

0
AndyG On

*ptr returns to you an instance of type of things, for which there is no operator << defined, hence the compile-time error.

A struct is not the same as an array. That is, it doesn't necessarily decay to a pointer to its first element. The compiler, in fact, is free to (and often does) insert padding in a struct so that it aligns to certain byte boundaries. So even if a struct could decay in the same way as an array (bad idea), simply printing it would not guarantee printing of the first element!

I mean a C-Style array like int[]

These boundaries are implementation-dependent and can often be controlled in some manner via preprocessor statements like pragma pack

0
Richard Hodges On

I found out that address of first element of structure is same as the address of structure.

Wherever you found this out, it wasn't the c++ standard. It's an incorrect assumption in the general case.

There is nothing but misery and pain for you if you continue down this path.

0
Laszlo On

Try any of these:

#include <iostream>
#include <cstring>

struct things{
    int good;
    int bad;
};

int main()
{
    things *ptr = new things;
    ptr->bad = 3;
    ptr->good = 7;

    std::cout <<  *(int*)ptr << std::endl;
    std::cout <<  *reinterpret_cast<int*>(ptr) << std::endl;

    int* p = reinterpret_cast<int*>(ptr);
    std::cout <<  *p << std::endl;
    return 0;
}