A code to test: (Gives the occupation in structure, not the size).
#include <stdio.h>
struct P1
{
short i;
int c;
int *j;
short *d;
long long end[];
};
struct P4
{
char w[16];
char *c[2];
long long end[];
};
struct P5
{
struct P4 a[2];
struct P1 t;
long long end[];
};
int main(void)
{
struct P1 p1;
printf("size of p1 : %zu\n", sizeof(p1));
printf("short i : %zu\n", (size_t)&p1.c - (size_t)&p1.i);
printf("int c : %zu\n", (size_t)&p1.j - (size_t)&p1.c);
printf("int *j : %zu\n", (size_t)&p1.d - (size_t)&p1.j);
printf("short *d : %zu\n", (size_t)&p1.end - (size_t)&p1.d);
struct P4 p4;
printf("\nsize of p4 : %zu\n", sizeof(p4));
printf("char w[16] : %zu\n", (size_t)&p4.c - (size_t)&p4.w);
printf("char *c[2] : %zu\n", (size_t)&p4.end - (size_t)&p4.c);
struct P5 p5;
printf("\nsize of p5 : %zu\n", sizeof(p5));
printf("struct P4 a[2] : %zu\n", (size_t)&p5.t - (size_t)&p5.a);
printf("struct P1 t : %zu\n", (size_t)&p5.end - (size_t)&p5.t);
return 0;
}
- The flexible member array is just to mark the end.
Following Gerhardh's remark, code with offsetof.
#include <stdio.h>
#include <stddef.h>
struct P1
{
short i;
int c;
int *j;
short d;
long long end[];
};
int main(void)
{
struct P1 p1;
printf(" Offset Size Occupation\n");
printf("short i : %12zu %12zu %12zu\n", offsetof(struct P1, i), sizeof(p1.i), offsetof(struct P1, c));
printf("int c : %12zu %12zu %12zu\n", offsetof(struct P1, c), sizeof(p1.c), offsetof(struct P1, j)-offsetof(struct P1, c));
printf("int *j : %12zu %12zu %12zu\n", offsetof(struct P1, j), sizeof(p1.j), offsetof(struct P1, d)-offsetof(struct P1, j));
printf("short *d : %12zu %12zu %12zu\n", offsetof(struct P1, d), sizeof(p1.d), offsetof(struct P1, end)-offsetof(struct P1, d));
printf("end : %12zu \n", offsetof(struct P1, end));
return 0;
}