Size of a structure considering padding with strings and int as element

69 Views Asked by At

I want to know how the following structure is stored in memory.
The given structure size is shown 28 by using sizeof(). I want to know why it is so?

typedef struct {
    char a[10];
    int c;
    char b[10];
}example4;

printf("%ld\n", sizeof(example4));

I already know about padding, but don't know how does it apply for strings with different length. I used the following printf to know the memory address

printf("%p %p %p %p %p\n", (void*)&(example4.a), (void*)&(example4.b), (void*)&(example4.c), (void*)&(example4.a[0]), (void*)&(example4.b[0]));

but it didn't work.

2

There are 2 best solutions below

0
wohlstad On

You get a compiler error, because in order to print addresses of variables you need a concrete instance (and example4 is a type, not an instance):

example4 ex4;
printf("%p %p %p %p %p\n", 
                  (void*)&(ex4.a), 
                  (void*)&(ex4.b), 
                  (void*)&(ex4.c), 
                  (void*)&(ex4.a[0]), 
                  (void*)&(ex4.b[0]));

This is the output I get (specific in my environment):

000000707F55F6B8 000000707F55F6C8 000000707F55F6C4 000000707F55F6B8 000000707F55F6C8

So the layout I infer (again in my environment) is:
a - 12 bytes (with padding)
c - 4 bytes
b - 12 bytes (with padding)
Total: 28 bytes (which matches the result reported in your test).

(it's a bit confusing because the fields names are not according to they position in the struct, but I followed you code as is).

Note that layout can change between compilers and systems but my result seem to be in line with yours and therefore explains what you observed.

Another issue is that the proper printf format specifier for size_t is %zu:

printf("%zu\n", sizeof(example4));
0
Kuba hasn't forgotten Monica On

Layout of the structures can be easily explored using the offsetof macro from stddef.h. The program below will output the results you want on pretty much every mainstream platform.

#include <stddef.h>
#include <stdio.h>

typedef struct {
    char a[10];
    int c;
    char b[10];
} Example4;

int main() {
    printf("a:     %zu\n", offsetof(Example4, a));
    printf("c:     %zu\n", offsetof(Example4, c));
    printf("b:     %zu\n", offsetof(Example4, b));
    printf("total: %zu\n", sizeof(Example4));
}