结构体与指针
例程1
typedef struct
{
unsigned int a;
unsigned int b;
unsigned int c;
}Test_T;
void main(void)
{
Test_T Temp;
Test_T *Test;//指向数组的指针
Test=&Temp;
Temp.a=0;
Temp.b=1;
Temp.c=2;
*(unsigned int *)((unsigned int)&(Test->a)+0)+=5;
*(unsigned int *)((unsigned int)&(Test->a)+4)+=1;
*(unsigned int *)((unsigned int)&(Test->a)+8)+=4;
printf("a=%d,b=%d,c=%d\n",Temp.a,Temp.b,Temp.c);
printf("sizeof(unsigned int)=%d\n",sizeof(int));
printf("sizeof(Test_T)=%d\n",sizeof(Test_T));
printf("&Temp.a=%d\n",&Temp.a);
printf("&Temp.b=%d\n",&Temp.b);
printf("&Temp.c=%d\n",&Temp.c);
printf("Test=%d\n",*Test);
printf("Test=%d\n",Test);
printf("Test+1=%d\n",Test+1);
printf("Test+1=%d\n",Test+2);
}
输出结果
Test为指向结构体的指针,Test值为存放结构体内存的首地址,Test+1实际上指针移动了3*sizeof(unsigned int)。可以通过*Test来查询结构体中第一个成员的值
例程2
typedef struct
{
unsigned int a[2];
unsigned int b;
unsigned int c;
}Test_T;
void main(void)
{
Test_T Temp;
Test_T *Test;//指向数组的指针
Test=&Temp;
Temp.a[0]=8;
Temp.b=1;
Temp.c=2;
printf("sizeof(unsigned int)=%d\n",sizeof(int));
printf("sizeof(Test_T)=%d\n",sizeof(Test_T));
printf("&Temp.a=%d\n",&Temp.a[0]);
printf("&Temp.b=%d\n",&Temp.b);
printf("&Temp.c=%d\n",&Temp.c);
printf("Test=%d\n",Test);
printf("*Test=%d\n",*Test);
}
输出结果