0

I am trying to understand how does a array of structs look like in memory. Suppose I have the following

struct b{
     int x;
     int y;
     int z;
};
b barray[100];

So now barray is an array of structs where barray is the pointer to the 1st struct i.e. barray=&barray[0]. If int is taking 2 bytes and then say the struct b takes 6 bytes and lets say barray = 1000 and the size of pointer is say 4 bytes. Then is barray+1=1004 or is it 1006? I mean is the array an array of pointers each pointing to its instance of the structure or are all the 100 structures placed in a continuous memory location and incrementing the index of the array jumps to the next struct?

Milind
  • 415
  • 8
  • 24

1 Answers1

2

An array is a contiguous block of memory in c, so an array of structs will have a size of sizeof(struct b)*number_of_structs. All of the structs are allocated within the array.

Note that in your example sizeof(struct b) is not guaranteed to be 6 because the compiler is allowed to insert padding to byte align the structs - you can use "packed" to avoid this if you like but it may hinder performance. Structure padding and packing

Steve
  • 939
  • 1
  • 6
  • 20