8.3 结构体指针变量

结构体就是变量,变量可通过变量名和地址访问

结构体指针变量的定义:

结构体实际上就是自己定义的变量类型,所以结构体指针与整型、字符、浮点类型如出一辙

char c;
char *pc = &c;
	
struct Test t1;
struct Test *ps = &t1;

而定义一个指向结构体的指针,保存的是结构体的地址

通过结构体指针访问结构体:

通过指针变量间接访问结构体时用“->”运算符

	printf("t1的idata=%d\n",t1.idata); //.运算符
	printf("t1的idata=%d\n",ps->idata); //->运算符

    ps->cdata ='r';                    //通过指针变量修改结构体变量
    printf("t1的idata=%c\n",t1.cdata); //.运算符
	printf("t1的idata=%c\n",ps->cdata); //->运算符

应用:

#include 
#include 

struct Student
{
	int num;
	char name[32];
	char sex;
	int age;
	double score;
	char addr[32];
};
int main(){
	int arr[3]= {1,2,3};
	int i;
	int len;
	
	struct Student arry[3]={
		{2,"张三",'m',18,97.5,"北京"},
		{3,"李四",'m',18,98.5,"上海"},
		{4,"王五",'f',18,99.5,"广州"}
	};
	len = sizeof(arr)/sizeof(arr[0]);
	

    struct Student *p;
    p = arry;
	for(i=0;inum,p->age,p->score,p->name,p->addr);
    p++;
	}
     p = arry; //再次打印时,指针归位
    for(i=0;inum,p->age,p->score,p->name,p->addr);
    p++;
	}
	return 0;
}

你可能感兴趣的:(C语言,c语言)