Shanqing Cai
Shanqing Cai

Reputation: 3876

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?

Upvotes: 8

Views: 2922

Answers (2)

haccks
haccks

Reputation: 105992

The above structure declaration just inform the compiler that variables of that struct data structure type will take sizeof(struct0_T) bytes of memory and this memory will be allocated once a variable of that type will be instantiated.

struct0_T s;

Now, s contains an array of two doubles. There will be no padding in this case.

Upvotes: 2

caf
caf

Reputation: 239011

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.

Upvotes: 10

Related Questions