结构体相关案例

格式: struct 结构体名字 {

          成员;

          成员;

          成员;

          ……;

   }

起别名:

格式: typedef  struct 结构体名字 {

          成员;

          成员;

          成员;

          ……;

   }别名             

注意:此时的结构体的名字可有可无,

      后面如果要使用该结构体直接使用别名即可

案例1:

定义一个结构体表示学生
学生的属性有:姓名、年龄
要求把这三个学生信息放入到数组当中,并遍历数组

#include<stdio.h>
#include<string.h>

struct Student
{  
	char name[100];
	int age;
};   //先定义一个结构体来存放学生的属性
//01
int main() {
	struct Student stu1 = { "张三",18 };    //定义变量并给其赋值
	struct Student stu2 = { "张四",19 };
	struct Student stu3 = { "张五",20 };
	struct Student arr[3] = { stu1,stu2,stu3 };

	for (int i = 0; i < 3; i++) {
		struct Student x = arr[i];      //创建一个struct Student 类型的变量
                                        //承接数组中的元素
		printf("第%d个学生的姓名是%s 年龄是%d\n", i+1, x.name, x.age);
	}
}

 

第二种方法:

#include<stdio.h>
#include<string.h>

struct Student
{  
	char name[100];
	int age;
};   //先定义一个结构体来存放学生的属性


int main() {
	struct Student stu1 ;
	strcpy(stu1.name, "张三");
	stu1.age = 18;

	struct Student stu2;
	strcpy(stu2.name, "张四");
	stu2.age = 19;

	struct Student stu3;
	strcpy(stu3.name, "张五");
	stu3.age = 20;
	struct Student arr[3] = { stu1,stu2,stu3 };

	for (int i = 0; i < 3; i++) {
		struct Student x = arr[i];
		printf("第%d个学生的姓名是%s 年龄是%d\n", i + 1, x.name, x.age);
	}
}

 

案例2:

定义一个结构体表示学生
学生的属性:姓名,年龄
定义一个函数修改学生的中的数据

#include<stdio.h>
#include<string.h>

 typedef struct Student
{ 
	char name[100];
	int  age;
}s;  //取别名代替struct Student

 //定义一个函数修改学生的中的数据

 void fun(s* p) {
	 s x = *p;
	 strcpy(x.name, "李四");
	 x.age = 20;
	 printf("修改后的学生消息为:%s %d", x.name, x.age);

 }
int main() {

	s sutdent1 = { "张三",10 };
	s y = sutdent1;
	printf("修改前的学生消息为:%s %d\n", y.name, y.age);
	printf("---------------------------------\n");
	fun(&y);
}

 

案例3:

结构体的嵌套
定义一个结构体表示学生
里面的成员如下:姓名,年龄,联系方式
其中联系方式也是一个结构体里面包含手机号,电子邮箱
 

#include<stdio.h>
#include<string.h>


//定义联系方式结构体

  struct  contact
{
	char eamil[100];
	int tell[100];
};


typedef struct {
	char name[100];
	int  age;
	struct  contact  c;    //调用联系方式结构体并声明一个变量
}s;


 int main() {
	 s stu ;
	 strcpy(stu.name, "小明");
	 stu.age = 20;
	 strcpy(stu.c.eamil, "2070143895@qq.com");
	 strcpy(stu.c.tell, "12345678910");

	 printf("姓名:%s\n", stu.name);
	 printf("年龄:%d\n", stu.age);
	 printf("电子邮箱:%s\n", stu.c.eamil);
	 printf("手机号码:%s", stu.c.tell);
}

  • 14
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值