//C语言中结构体中的成员域偏移量
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct _student{
char name[];//
int num;
}Student;
void main(){
Student *p = NULL;
printf("%x\n", p);//打印 0
p = p - ;
printf("%x\n",p);//打印ffffdc
//说明 指针的加法运算前面已有详述,p - 1移动了 sizeof(Student)个字节
//由于结构体字节对齐原则,char name[30]数组占据32个字节,不是30个,不明白请看结构体那一章
//计算出p的步长是 32+4=36
p = p - ;
printf("%x\n", p);//打印ffff94
p = p + ;
printf("%x\n", p);//打印ffffdc
//说明:以上两个的解释同p-1
p = (Student *);
p = p - ;
printf("p - 1=%x\n", p);//打印ffffdd
p = (Student *);
p = p - p;
//警告:警告 1 warning C4047: “=”:“Student *”与“int”的间接级别不同 tec01.c 33 1 C005
//警告产生原因是p-p得出的值是int型 p是Student *类型
//由此说明:p - p和p-1有所区别,p-p只是单纯的p的值加减,p-p=0,返回值是int型,而p-1是指针间的运算,返回值是指针
printf("p - p=%x\n", p);//打印0
//结构体指针中 . ->操作符本质上是寻址,寻找每一个成员相对于结构体起始位置的内存偏移,
//该操作在cpu里执行,不会操作内存,所以 p->num等价于 ((Student *)0)->num 因为不会操作内存,所以不会报错
printf("%x\n", &(p->num));//打印20 (此处是16进制)
//说明 &(p->num)是取p->num得地址 num相对于结构体起始位置的内存偏移量是char name[30] 32个字节(结构体字节对齐原则)
system("pause");
}
