Dereference a structure to get value of first member

浪子不回头ぞ 提交于 2020-01-05 07:12:13

问题


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;
}

回答1:


*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




回答2:


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;
}



回答3:


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!!




回答4:


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.



来源:https://stackoverflow.com/questions/41506788/dereference-a-structure-to-get-value-of-first-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!