In the space to see other people's doubts aroused my interest, just the topic I am interested in, just write it. For other people's Questions, also published in the QQ space. Because it is late to work, 10 o ' clock to get home, published also late. Actually, it's a simple question.
Direct use of examples and memory diagram description:
#include <iostream>usingstd::cout;usingstd::cin;structstu{Charsex; intlength; Charname[Ten];}; voidMain () {Stu stu0; Stu0.sex='F'; Stu0.length=1; stu0.name[0] ='a'; stu0.name[1] ='b'; stu0.name[2] ='C'; stu0.name[3] ='D'; stu0.name[4] ='e'; stu0.name[5] ='F'; stu0.name[6] ='g'; stu0.name[7] ='h'; stu0.name[8] ='I'; stu0.name[9] ='J'; intSize =sizeof(STU0); Stu*p_stu = &stu0; cout<<size; Cin.Get();}
The result is: 20 bytes. Obviously there is a process of memory alignment.
Set a breakpoint at VS, toggle disassembly, then see the memory location of the struct with the pointer, then look at the memory Viewer vs provides:
Relative to the program content, you can clearly see how the memory is distributed.
The first four bytes store char type-66, then four bytes Store int 01 Then 10 bytes is a char array, followed by 2 bytes, total 20 bytes. Obviously, the amount of memory here is 4.
The above is padded in 4, because the largest is int, four bytes.
Let's look at the following example:
#include <iostream>usingstd::cout;usingstd::cin;structstu{Charsex; Doublelength; Charname[Ten];}; voidMain () {Stu stu0; Stu0.sex='F'; Stu0.length=1.1; stu0.name[0] ='a'; stu0.name[1] ='b'; stu0.name[2] ='C'; stu0.name[3] ='D'; stu0.name[4] ='e'; stu0.name[5] ='F'; stu0.name[6] ='g'; stu0.name[7] ='h'; stu0.name[8] ='I'; stu0.name[9] ='J'; intSize =sizeof(STU0); Stu*p_stu = &stu0; cout<<size; Cin.Get();}
The result is 32.
The description is filled in 8 (double), the first char is 8 bits, the second double8 bit, and then the char array is 10 bits, followed by 6 bits. Total 32 bits.
Therefore, in summary, the struct memory completion mechanism, is to use the largest data type units to be padded. Arrays are stored continuously in a space.
Know the above I summed up a point, combined with the VS memory graph, will be counted, the struct memory size.
You will find that my article has been tangled in what units to memory.
Because this unit is the most critical problem.
If you find a unit that is filled with memory, you will naturally calculate it.
I also verified the view that the unit is the largest data type in a struct by a small experiment.
As for why memory is needed, of course, the compiler optimizes for CPU addressing. If you do not have memory, xxxxxxx (Thousands of words in the middle) addressing how much trouble you know?
The problem of internal alignment in C struct structure