Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory layout of C struct with arrays

Suppose I have a C struct defined as follows:

typedef struct 
{
  double array1[2];
} struct0_T;

How is the memory laid out? Is struct going to hold just a pointer or the value of the two doubles? Before I thought the struct holds a pointer, but today I found out (to my surprise) that the values are stored there. Does it vary between different compilers?

like image 814
Shanqing Cai Avatar asked Apr 22 '15 13:04

Shanqing Cai


1 Answers

The struct contains the two values. The memory layout is .array1[0], followed by .array1[1], optionally followed by some amount of padding.

The padding is the only part that of this that can vary between compilers (although in practice, with the only member of the struct being an array there will almost certainly be no padding).

Although you may have heard that an array in C is a pointer, that is not true - an array is an aggregate type consisting of all the member objects, just like a struct. It is just that in almost all expression contexts, an array evaluates to a pointer to its first member.

like image 58
caf Avatar answered Nov 07 '22 04:11

caf