0
struct stu{
    char a;
    int b;
    char c;
};

int main(){
    struct stu stu1;
    stu1.b = 12;
    struct stu stu2;
    stu2.b = 10;
    return 0;
}

the address of each element is shown below:

&stu1
0x7fffffffe000
&stu1.a
0x7fffffffe000
&stu1.b
0x7fffffffe004
&stu1.c
0x7fffffffe008
&stu2
0x7fffffffe010
&stu2.a
0x7fffffffe010
&stu2.b
0x7fffffffe014
&stu2.c
0x7fffffffe018

why there are 4 bytes (0x7fffffffe0c~0x7fffffffe00f) between the 2 structs

ps:also, if the 2 structs are only defined without initilized, the address of them are the same, why?

derong
  • 1

1 Answers1

0

It's for speed reasons. Reading/writing the whole (d)(q)words (aligned to actual physical memory structure) is much faster. You can also see it takes 4 bytes for a single char (addr. of b - addr. of a = 4, not 1).

If you want to avoid it, make a single structure and use #pragma pack.

Proper data grouping can make your program faster (because most read/write operations are done with whole qwords).

NickDoom
  • 339
  • 1
  • 9
  • thank you so much! And, why the addr. of the 2 structs is the same if they are only defined without initialized? is it "copy-on-write" ? – derong Mar 14 '19 at 01:40
  • Optimisation. If you assign a value to stu1, use it somehow, assign a value to stu2 and never use stu1 beyond this point, the compiler may decide two structures are too much, and reuse the existing one. Old-timers do this manually, but it requires some attention, it's easy to forget which structures can be reused, and which are busy (and to corrupt data). Also, counters like I, J, K are often declared once and get re-used several times in loops. With this option, you can declare a counter for each loop and compiler will optimise them to the minimal set, preventing occasional re-use a busy one. – NickDoom Mar 14 '19 at 13:05