Skip to content

Instantly share code, notes, and snippets.

@pjhades
Created January 8, 2015 16:44
Show Gist options
  • Save pjhades/ea136c9bdf5b14795cfb to your computer and use it in GitHub Desktop.
Save pjhades/ea136c9bdf5b14795cfb to your computer and use it in GitHub Desktop.
Memory alignment cases.
#include <stdio.h>
struct P1 { int i; char c; long j; char d; };
struct P2 { long j; char c; char d; int i; };
struct P3 { short w[3]; char c[3]; };
struct P4 { short w[3]; char *c[3]; };
struct P5 { struct P1 a[2]; struct P2 *p; };
int main()
{
struct P1 p1;
struct P2 p2;
struct P3 p3;
struct P4 p4;
struct P5 p5;
printf("struct P1 { int i; char c; long j; char d; };\n");
printf("total=%lu, offsets: %ld %ld %ld %ld\n\n", sizeof(p1), (unsigned char *)&p1.i - (unsigned char *)&p1, (unsigned char *)&p1.c - (unsigned char *)&p1, (unsigned char *)&p1.j - (unsigned char *)&p1, (unsigned char *)&p1.d - (unsigned char *)&p1);
printf("struct P2 { long j; char c; char d; int i; };\n");
printf("total=%lu, offsets: %ld %ld %ld %ld\n\n", sizeof(p2), (unsigned char *)&p2.j - (unsigned char *)&p2, (unsigned char *)&p2.c - (unsigned char *)&p2, (unsigned char *)&p2.d - (unsigned char *)&p2, (unsigned char *)&p2.i - (unsigned char *)&p2);
printf("struct P3 { short w[3]; char c[3] };\n");
printf("total=%lu, offsets: %ld %ld\n\n", sizeof(p3), (unsigned char *)&p3.w - (unsigned char *)&p3, (unsigned char *)&p3.c - (unsigned char *)&p3);
printf("struct P4 { short w[3]; char *c[3]; };\n");
printf("total=%lu, offsets: %ld %ld\n\n", sizeof(p4), (unsigned char *)&p4.w - (unsigned char *)&p4, (unsigned char *)&p4.c - (unsigned char *)&p4);
printf("struct P5 { struct P1 a[2]; struct P2 *p; };\n");
printf("total=%lu, offsets: %ld %ld\n\n", sizeof(p5), (unsigned char *)&p5.a - (unsigned char *)&p5, (unsigned char *)&p5.p - (unsigned char *)&p5);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment