Search code examples
clinuxstructembedded-linux

Exactly why is the size of this struct 32?


I needed help in finding the size of the struct below

#include <stdio.h>
struct bottle{
    float* weight;
    int* qnty;
    char* type;
    char* color;
};

int main(){
    printf("%zu\n", sizeof(struct bottle));
    return 0;
}

I got the output as 32 but I'm not getting how it derived with that value and I want someone to explain why it is 32.

PS: I'm using a Linux compiler.


Solution

  • Due to the provided result, I assume you are on a 64-bit machine. This means that your system most probably has a 64-bit address bus, so the addresses it can address are 64 bits wide.

    Most of the time, C pointers are implemented as direct virtual memory addresses and are the same width as the address bus (in your case, 64 bits).

    /* 64 bits = 8 bytes */
    
    struct bottle {
        float *weight; /* 8 bytes */
        int *qnty;     /* 8 bytes */
        char *type;    /* 8 bytes */
        char *color;   /* 8 bytes */
    };
    
    /* Grand total: 32 bytes */
    

    On a 32-bit machine, this would be 16 bytes.