C语言指针练习03-指向结构体变量的指针
在C语言中,结构体变量的指针就是该变量在内存中的起始地址。如果声明指针变量,指向结构体变量,则这个指针变量的值是结构体变量的首地址。
我们通过一个示例,使用指针变量实现显示学生信息,来说明通过指针访问结构体变量。
声明结构体
struct Student{
int num;
char name[20];
int age;
};
声明一个Student结构体,包含num,name,age三个成员。
创建结构体变量
struct Student st = {001, "王五",30};
创建结构体变量st,进行赋值。
创建结构体指针变量
struct Student *pst;
pst = &st;
创建结构体指针变量pst,将结构体变量st的首地址赋值给指针变量pst。
指针访问
printf("Number:%d\n",pst->num);
printf("Name:%s\n",pst->name);
printf("age:%d\n",pst->age);
使用指针变量pst访问结构体中的成员,通过pst->成员变量的形式进行访问
完整示例
#include<stdio.h>
struct Student{
int num;
char name[20];
int age;
};
int main(void){
struct Student st = {001, "王五",30};
struct Student *pst;
pst = &st;
printf("Number:%d\n",pst->num);
printf("Name:%s\n",pst->name);
printf("age:%d\n",pst->age);
return 0;
}