c语言结构体对齐例子

 

结构体里的变量8字节对齐     指的是相对于结构体首地址的偏移是8字节的整数倍

 

ldrexd的指令   要求的是被操作的内存地址的8字节对齐

 

p:0x56401b274264
p->a:0x56401b274264
p->b:0x56401b274268
p->c:0x56401b27426c
p->d:0x56401b274274
p->e:0x56401b27427c
p->f:0x56401b274284
p->g:0x56401b274288
a:0x7ffdfc13ee60
b:0x7ffdfc13ee64
c:0x7ffdfc13ee68
d:0x7ffdfc13ee70
 cat attribute.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct attr {
char a __attribute__((__aligned__(8)));
int b ;
double c __attribute__((__aligned__(8)));
long d __attribute__((__aligned__(8)));

char e __attribute__((__aligned__(2)));
char f __attribute__((__aligned__(8)));
char g __attribute__((__aligned__(4)));

}__attribute__((__aligned__(8)));
int main()
{
struct attr abc;
char * tmpp = malloc(sizeof(struct attr)+100);
struct attr *p =tmpp+4;
printf("p:%p\n",p);
printf("p->a:%p\n",&p->a);
printf("p->b:%p\n",&p->b);
printf("p->c:%p\n",&p->c);
printf("p->d:%p\n",&p->d);
printf("p->e:%p\n",&p->e);
printf("p->f:%p\n",&p->f);
printf("p->g:%p\n",&p->g);
abc.a = 1;
abc.b = 2;
abc.c = 3;
abc.d = 4;
printf("a:%p\n",&abc.a);
printf("b:%p\n",&abc.b);
printf("c:%p\n",&abc.c);
printf("d:%p\n",&abc.d);

}

有时候,不小心知道了一些事,才发现自己所在乎的事是那么可笑。