By studying structure lead me to a question that how structures are stored in the memory by compiler which means consider
struct
{
int number;
char name[nam];
}h;
what i want to know is how the members (here it is number
and name
) are stored (whether they are stored in sequence or stored in random place for instance if number is stored in address 2000 and name
is stored in 2990) ?
Memory is allocated in a sequence for structure members:
+------------+------------------+-----+-----+-----+-----+-----+-----+
| | ........ | | | | | | |
| | | | | | | | |
+------------+--------+---------+-----+-----+-----+-----+-----+-----+
+ + | name[0] name[nam-1]
+------+-----+ | +------------------+----------------+
| | |
| | |
v v v
number padding name[nam]
But, unlike arrays, the allocated memory for a structure may or may not be packed, i.e, there may be some padding after the allocated space of any member (but no padding is allowed before the first member).
You may find the answer in Data structure alignment:
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With