How does the c compiler allocate memory for structures?

Studying the structure, I come to the question of how the structure is stored in memory by the compiler, which means to consider

struct 
{
      int number;
      char name[nam];
 }h;

I want to know how the members are stored (here numberand name) (regardless of whether they are stored in sequence or stored in a random place, for example, if the number is stored in address 2000 and namestored in 2990)?

+4
source share
6 answers

The memory is allocated in sequence for members of the structure:

+------------+------------------+-----+-----+-----+-----+-----+-----+
|            |     ........     |     |     |     |     |     |     |
|            |                  |     |     |     |     |     |     |
+------------+--------+---------+-----+-----+-----+-----+-----+-----+
+            +        |       name[0]                             name[nam-1]
+------+-----+        |         +------------------+----------------+
       |              |                            |
       |              |                            |
       v              v                            v
    number         padding                      name[nam]

But, unlike arrays, the allocated memory for the structure may or may not be packed, i.e. there may be some filling after the allocated space of any member (but filling is not allowed before the first element).

+4

:

- , . , : .. , (, 4 32- ). , , - , . , .

+2

, .

+2

. , ( ):

enter image description here

+2

C99 6.7.2.1/13

, , . , , ( -, , ) . , .

, name number , . name, , .

+2

. , , char array[42] , , malloc .

, .

, , ( )

-1

All Articles