结构

  

一、结构的声明和初始化:写一个学生的结构体并打印出内容

  1 #include<stdio.h>

  2 

  3 struct student{

  4         int id;

  5         char name[10];

  6 }stu1;

  7 

  8 int main(){

  9 stu1.id=110;        // 赋值

 10 strcpy(stu1.name,"zhangfei");

 11 printf("%d,%s\n",stu1.id,stu1.name);

 12 

 13 struct student stu2={112,"lisa"};   //初始化

 14 printf("%d,%s\n",stu2.id,stu2.name);

 15 

 16 return 0;

 17 }

二、结构做参数

  1 #include <stdio.h>                                                         

  2 #include <string.h>

  3 struct student{

  4         int id;

  5         char name[10];

  6 }stu;

  7 

  8 

  9 void print1(struct student stu){

 10 printf("%d,%s\n",stu.id,stu.name);

 11 }

 12 

 13 void print2(struct student *p){

 14 printf("%d,%s\n",p->id,p->name);

 15 }

 16 

 17 

 18 int main(){

 19 stu.id=110;

 20 strcpy(stu.name,"zhangfei");

 21 

 22 struct student stu2={112,"lisa"};

 23 print1(stu);

 24 print2(&stu2);

 25 return 0;

 26 } 

三、结构做返回值的代码

  1 #include <stdio.h>                                                         

  2 #include <string.h>

  3 struct student{

  4 int id;

  5 char name[10];

  6 };

  7 struct student input1(){

  8 struct student stu;

  9 printf("please input your id:\n");

 10 scanf("%d",&stu.id);

 11 printf ("please input you name:\n");

 12 scanf ("%s",&stu.name);

 13 return stu;

 14 }       

 15 void input2(struct student *p){

 16 printf("please input your id: ");

 17 scanf("%d",&p->id);

 18 printf("please input your name: ");

 19 scanf("%s",&p->name);

 20 }

 21 int main(){

 22 struct student stu;

 23 stu=input1();

 24 printf("%d,%s\n",stu.id,stu.name);

 25 input2(&stu);

 26 printf("%d,%s\n",stu.id,stu.name);

 27 return 0;

 28 }

猜你喜欢

转载自www.cnblogs.com/30ends/p/9221879.html
今日推荐