p没有操作内存,在cpu中运用不会出错。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct teacher
{
int id;
char name[64];
int age;
};
int main(void)
{
struct teacher t1 = {0};
struct teacher *p = &t1;
int age = t1.age;
int id = t1.id;
int id_offsize = (int)&(((struct teacher *)0)->id);
int name_offsize = (int)&(((struct teacher *)0)->name);
int age_offsize = (int)&(((struct teacher *)0)->age);
printf("id_off: %d, name_off:%d, age_off:%d\n", id_offsize, name_offsize, age_offsize);
int age_off = (int)(&(p->age)) - (int)p;
printf("age_off : %d\n", age_off);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#pragma pack(2) //8字节对⻬
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct A
{
char c; //1byte
double d; //8byte
short s; //2byte
int i; //4byte
};
struct B
{
int a;
//double d;
char c1;
char c2;
short s1;
short s2;
};
int main(void)
{
int size_A = 0;
size_A = sizeof(struct A);
printf("size_A : %d\n", size_A);
int size_B = 0;
size_B = sizeof(struct B);
printf("size_B : %d\n", size_B);
return 0;
}