#include<stdio.h>
int main(int argc,char *argv[])
{
//先定义一个结构体
struct student
{
char firstname[30];
char * lastname;
int score;
};//这个封号很重要,一定不能忘
//定义一个结构体变量和一个指向结构体的指针变量
struct student stu1,*stu2;
//结构体变量的赋值
printf("请输入stu1.firstname:\n");
scanf("%s",stu1.firstname);//在这儿不可以用str.name="xxxx",因为firstname是一个指针常量
printf("请输入stu1.lastname:\n");
stu1.lastname="小平";//lastname是一个字符指针,所以不能用scanf来输入,只能用赋值形式,除非提前分配内存空间
printf("请输入stu1.score:\n");
scanf("%d",&stu1.score);
//scanf("%s",str1.firstname);
//指针变量分配空间和赋值
stu2=(struct student *)calloc(1,sizeof(struct student));
printf("请输入stu2->firstname:\n");
scanf("%s",stu2->firstname);
printf("请输入stu2->lastname:\n");
stu2->lastname="小英";//这儿也不能用scanf来进行输入
printf("请输入stu2->score:\n");
scanf("%d",&stu2->score);
//输出两个结构体成员变量的值
printf("stu1.firstname=%s\n",stu1.firstname);
printf("stu1.lastname=%s\n",stu1.lastname);
printf("stu1.score=%d\n",stu1.score);
printf("\n");
printf("stu2->firstname=%s\n",stu2->firstname);
printf("stu2->lastname=%s\n",stu2->lastname);
printf("stu2->score=%d\n",stu2->score);
//调用free函数释放stu2的内存空间
free(stu2);
printf("这次还是多少呢stu2->score=%d\n",stu2->score);
system("PAUSE");
//输出两种结果
return 0;
} |
|