Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming ( Declaration of structs )

Tags:

c

When we declare say :

int array[2];

array = " Holds the address of the first 32 bits" i.e it holds &array[0]. So the "array" is a pointer. But when we declare a struct for example:

typedef struct x 
{
    int y;
    int array[2];
}

Why the size of this struct is 16 bytes ? shouldn't it be 8 bytes since "array" is a pointer ? I am so confused ?

like image 932
Vicky Avatar asked Mar 15 '23 03:03

Vicky


1 Answers

First up array here is an array with space allocated within the struct to contain all the elements of that array. It's not a pointer to space outside the struct. With regards to how much space everything takes up the easiest way to see what's going on here is just to run some sizeof checks here:

#include <stdio.h>
typedef struct x 
{
    int y;
    int array[2];
};

int main(void) {
    struct x test1;
    printf("sizeof(int) %zu \n", sizeof(int));
    printf("sizeof(test1) %zu \n", sizeof(test1));
    printf("sizeof(test1.array) %zu", sizeof(test1.array));
    return 0;
}

When run on ideone you get the 4, 12 and 8 here. http://ideone.com/pKBe1X On other systems I've run this I get similar results which leads me to believe that on your machine with your particular compiler options some padding has been added to your structs.

If sizeof(test1.y) + sizeof(test1.array) != sizeof(test1) then you have some padding added in. Adding something such as #pragma pack (ms compiler) or __attribute__((__packed__)) (gcc) will likely change this.

The reason padding would be added by your compiler is because on your particular system there is likely some benefit in terms of access to data speed from having data structures with this particular alignment (multiples of 16 bytes) in memory. For more on that I'd recommend having a look at the Wikipedia page on data structure alignment.

like image 163
shuttle87 Avatar answered Mar 23 '23 06:03

shuttle87