结构体是一种自己定义的数据结构,是一种非常好用和有用的东东,由于指针是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]
我一直没有高明白为啥会出现这个警告
程序本身没有什么复杂的,就是把结构体当作参数以及返回值,可以留住给大家学习结构体和指针的稍微做个参考!!!