IBM Developerhttps://developer.ibm.com/articles/pa-dalign/
#include <stdio.h>
struct __attribute__((packed, aligned(4))) picture{
int height;
char* data;
int width;
char* enconding;
};
int main(){
#pragma pack(show)
printf("size: %lu\n", sizeof(struct picture));
}
c - What is the meaning of "__attribute__((packed, aligned(4))) " - Stack Overflow
#include <stdio.h>
#include <string.h>
#pragma pack(push,4)
//#pragma pack(push)
//#pragma pack(4)
struct test
{
char e0;
short e1;
char e2;
int e3;
char e4;
long e5;
};
#pragma pack(pop)
int main(int argc, char* argv[])
{
#pragma pack(show)
struct test st;
#define For(chptr,x,y) for(char* (chptr) = (char*)&(x) + sizeof (x); (chptr) < (char*)&(y); (chptr)++)
//就是一个for语句的宏,懒得写那么多废话
For(chptr,st.e0,st.e1) *chptr = 0XFF;
For(chptr,st.e1,st.e2) *chptr = 0XFF;
For(chptr,st.e2,st.e3) *chptr = 0XFF;
For(chptr,st.e3,st.e4) *chptr = 0XFF;
For(chptr,st.e4,st.e5) *chptr = 0XFF;
For(chptr,st.e5,*(&st+1))*chptr = 0XFF;
char* ptr = (char*)&st;
for(size_t i = 0; i < sizeof(struct test); i++)
{
printf("%p : ",ptr);
printf("%X\n",*ptr++);
}
}
1.对当前结构体对齐
#include <stdio.h>
int main()
{
struct Cat
{
char name[20];
char dogclass;
int weight;
}__attribute__((packed));
//__attribute__((packed))表示对当前结构体不要进行对齐操作
struct Dog {
char name[20];
char dogclass;
int weight;
};
printf("%lu %lu\n",sizeof(struct Cat), sizeof(struct Dog));
return 0;
}