+ 3

How we can access elements of structure b?

struct a { int i; struct b { int j; char d[10]; }y; struct c{ int eh; float w; }x; }z; given &z.x

19th Apr 2017, 8:49 PM
Posi2
Posi2 - avatar
2 Réponses
+ 4
You can't.* "&z.x" is a address of an object of type "c", which has no notion of the outer structure in which it's defined. Of course, you can always declare a new instance of struct "b" using something like "a::b newB", but you can't access z's instance through "x". At least, not safely. *If you really wanted to, you could use the memory address of "x" and manipulate it to point at other members of "z" if you're careful about the memory layout and pay mind to padding. This isn't a good idea, though, because how much padding is added is up to the compiler. At the very least, you can be confident that they'll exist in memory in the order they're specified according to the standard. For example, this works under MSVC: z.y.j = 6; a::c* ptr = &z.x; std::cout << ((a::b*)((char*)ptr - sizeof(a::b)))->j << std::endl; // outputs 6
20th Apr 2017, 1:04 AM
Squidy
Squidy - avatar
+ 4
what is MSVC? I am solving it in c. padding concept I don't understand we can also use common method memory used by strcut c then we can access struct b
20th Apr 2017, 7:10 AM
Posi2
Posi2 - avatar