-2

I have just read Extending a struct in C and I don't seem to understand what certain part of the code does.
Here is his current code:

typedef struct A {
  int x;
}A;

typedef struct B {
  A a;
  int d;
}B;

void fn(){
  B *b;
  ((A*)b)->x = 10;
}

I wonder, how does ((A*)b)->x = 10; become the same as b->a.x = 10;?

How do you interpret that line of code?

EDIT

What do (A*) and (A*)b do?

Community
  • 1
  • 1
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • Please note that `b` must be initialized to point at a valid variable. – Lundin Mar 06 '14 at 13:58
  • possible duplicate of [Extending a struct in C](http://stackoverflow.com/questions/22218604/extending-a-struct-in-c) – Vality Mar 06 '14 at 14:49
  • The code example is the same word for word and the question is nearly identical, this is nearly certainly a duplicate. – Vality Mar 06 '14 at 14:51

3 Answers3

3

According to the standard, a pointer to a structure must equal the pointer to the initial member of that structure. In other words, there must be no padding inserted into struct B in front of its region dedicated to storing the content of struct A. That is why the cast is valid:

Layout of struct B

Section 6.7.2.1.13

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Try visualize how struct B is stored in memory you will understand why they are equal.

struct B in memory is placed as a which is struct A followed by member d sequentially.

Now when you look at ((A*)b), it is strcut B casted to struct A which has member x in memory at zeroth offset.

Below is struct B in typical memory layout,

+--------------+
|      |       |
|  A   |   d   | 
|      |       |
+--------------+

and now if you expand it little more,

+--------------+
|      |       |
|  x   |   d   | 
|      |       |
+--------------+
Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46
2

If you check the memory layout of the structure A it looks like this

+---+
| x |
+---+

And if you then compare it to the memory layout of B it looks like this:

+---+---+
| x | d |
+---+---+

When you look at it like that it's easier to see why it works.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621