结构体指针变量
引入:
指针就是地址,指针变量就是存放地址的变量
int a;
int *p;
p=&a;
结构体也是变量
变量访问有两种方式:1.变量名 2.地址
struct Test t;
struct Test *P;
p=&t;
通过结构体指针访问结构体:用’->'来访问
#include <stdio.h>struct Test
{int idata;char cdata;
};int main()
{int a = 10;int *pa = &a;char c = 'c';char *pc = &c;struct Test t1 = {10,'c'}; //1.变量类型;2.变量名;3.变量值;4.变量地址;struct Test *ps = &t1;printf("t1的idata=%d\n",t1.idata);//变量名访问,用点运算符printf("t1的idata=%d\n",ps->idata);//结构体指针间接访问,用"->"运算符ps->cdata = 'R';//修改cdata的数据printf("t1的cdata=%c\n",t1.cdata);//变量名访问,用点运算符printf("t1的cdata=%c\n",ps->cdata);//结构体指针间接访问,用"->"运算符return 0;
}
1.用结构体指针输出
#include <stdio.h>
#include <string.h>struct Student
{int num;char name[32];char sex[32];int age;double score;char addr[32];
};int main()
{int i;struct Student arr[3] = {{2,"小王","男",22,99,"上海"},{3,"张三","男",20,77,"北京"},{4,"李四","女",18,66,"西安"}};struct Student *p;p = arr;int len = sizeof(arr)/sizeof(arr[0]);for(i = 0;i < len;i++){printf("学号:%d, 年龄:%d, 分数:%.2f, 姓名:%s, 性别:%s, 地址:%s\n",p->num,p->age,p->score,p->name,p->sex,p->addr);p++;}p = arr;for(i = 0;i < len;i++){printf("学号:%d, 年龄:%d, 分数:%.2f, 姓名:%s, 性别:%s, 地址:%s\n",p->num,p->age,p->score,p->name,p->sex,p->addr);p++;}return 0;
}