9

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?

5
  • 3
    It will hold the values. And no, it does not differ between compilers. Commented Apr 22, 2015 at 13:21
  • 1
    If it did hold just a pointer, where would the data be? Commented Apr 22, 2015 at 13:24
  • 1
    arrays are not pointers. In some situations arrays decay to pointer. This is definitely not one of those situation. Commented Apr 22, 2015 at 13:25
  • @DanielDaranas, I thought the data would be stored at the location pointed to by the pointer in the struct. Apparently this was wrong. Commented Apr 22, 2015 at 13:26
  • Does this answer your question? Array of structure Layout in Memory Commented Aug 21, 2022 at 18:55

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Arrays cannot have padding bytes, structs can.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.