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.
You get a compiler error, because in order to print addresses of variables you need a concrete instance (and
example4is a type, not an instance):This is the output I get (specific in my environment):
So the layout I infer (again in my environment) is:
a- 12 bytes (with padding)c- 4 bytesb- 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
printfformat specifier forsize_tis%zu: