C语言进阶(牟海军)C 语言指针理解 续(2)

本文通过一个具体的程序实例介绍了如何在C语言中使用结构体与指针,包括输入输出学生信息、查找年龄最大及姓名最小的学生,并分析了程序中存在的警告原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

结构体是一种自己定义的数据结构,是一种非常好用和有用的东东,由于指针是C语言的灵魂,那么说到这儿,有一个很显然的问题就是指针和结构体是否可以联系起来。

很显然一定要把指针指向结构体

先看一个例子

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

struct stu
{
	char name[10];
	char sex[10];
	int age;
};

struct stu find_max(struct stu stu1[],int n);
struct stu find_min(struct stu stu1[],int n);
void show_information(struct stu stu1[],int n);
void print(struct stu stu1);
void input(struct stu stu1[],int n)//input information
{
	int i;
	for(i=0;i<n;i++)
	{
		printf("please input name,sex and age:\n");
		scanf("%s%s",&stu1[i].name,&stu1[i].sex);
		fflush(stdin);
		scanf("%d",&stu1[i].age);
	}
	//return ;
}

struct stu find_max(struct stu stu1[],int n)//find the max age student
{
	int i;
	int index = 0;
	int temp = stu1[0].age;
	for(i=1;i<n;i++)
	{
		if(temp<stu1[i].age)
			{
				temp = stu1[i].age;
				index = i;
			}
		
	}
	return stu1[index];
}

struct stu find_min(struct stu stu1[],int n)//find the min name student
{
	char temp[10];
	int i,index = 0;
	strcpy(temp,stu1[0].name);
	for(i=1;i<n;i++)
	{
		if(strcmp(temp,stu1[i].name)>0)
			{
				strcpy(temp,stu1[i].name);
				index = i;
			}
	}
	return stu1[index];
}

void show_information(struct stu stu1[],int n)//print information
{
	int i;
	for(i=0;i<n;i++)
	{
		printf("the name is:%s\t",stu1[i].name);
		printf("the sex is:%s\t",stu1[i].sex);
		printf("the age is:%d\n",stu1[i].age);
	}
}

void print(struct stu stu1)
{
	 printf("the name is:%s\t",stu1.name);
         printf("the sex is:%s\t",stu1.sex);
         printf("the age is:%d\n",stu1.age);
}

int main()
{
	int number;
	printf("please input a number:\n");
	scanf("%d",&number);
	struct stu *stu1 = (struct stu*)malloc(sizeof(struct stu)*number);
	int i;
	//struct stu stu1[number];
	printf("please input %d student's information!",number);
	input(stu1,number);
	printf("the information of student is:\n");
	show_information(stu1,number);
	printf("the max age student is:\n");
	print(find_max(stu1,number));
	printf("the min name student is:\n");
	print(find_min(stu1,number));
	return 0;
}

该程序有一个问题,就是

11.c:22:3: 警告: 格式 ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[10]’ [-Wformat]
11.c:22:3: 警告: 格式 ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘char (*)[10]’ [-Wformat]

我一直没有高明白为啥会出现这个警告

程序本身没有什么复杂的,就是把结构体当作参数以及返回值,可以留住给大家学习结构体和指针的稍微做个参考!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值