結構體是一種自己定義的數據結構,是一種非常好用和有用的東東,由於指針是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]
我一直沒有高明白爲啥會出現這個警告
程序本身沒有什麼複雜的,就是把結構體當作參數以及返回值,可以留住給大家學習結構體和指針的稍微做個參考!!!