指向结构体变量的指针的简单应用
#include <stdio.h>
void main()
{
struct student/*声明结构体*/
{
/*结构体成员*/
long num;
char name[20];
char sex;
float score;
};
struct student stu_1;/*定义结构体类型的变量*/
struct student *p;/*定义结构体类型的指针变量*/
p=&stu_1;/*指向结构体变量的起始地址*/
stu_1.num=89101;/*对结构体成员赋值*/
strcpy(stu_1.name,"Li Lin");
stu_1.sex='M';
stu_1.score=89.5;
printf("NO:%ld\n name:%s\n sex:%c \n score:%f\n",stu_1.num,stu_1.name,stu_1.sex,stu_1.score);
/* (*p)表示p指向的结构体变量,(*p).num 是p指向的结构体变量中的成员*/
printf("NO:%ld\n name:%s\n sex:%c\n score:%f\n",(*p).num,(*p).name,(*p).sex,(*p).score);
system("pause");
}
指向结构体数组的指针
#include <stdio.h>
struct student
{
int num;
char name[20];
char sex;
int age;
};
/*指向结构体类型的数组的初始化*/
struct student stu[3]={{10101,"Li Lin",'M',18},{10102,"Zhang Fun",'M',19},
{10104,"Wang Min",'F',20}};
void main()
{
struct student *p;/*指向结构体类型的指针变量*/
printf("NO Name Sex Age\n");
for(p=stu;p<stu+3;p++)/*循环地址*/
{
/* printf("%5d%-20s %2c %4d\n",p->num,p->name,p->sex,p->age); 等价于*/
printf("%5d%-20s %2c %4d\n",(*p).num,(*p).name,(*p).sex,(*p).age);
}
system("pause");
}
写的是不难,难的是天天坚持写!