C语言结构体的用法,

结构体类型定义如下:
struct date{int year; int month; int day;}; //定义日期结构体类型
struct student
{ char name[20];
struct date birth; //出生日期
};
结构体数组s存储了n个人的名字和出生日期。写一函数,求这n个人中年龄最大(即出生日期最小)者的姓名。
要求实现下列函数:
char *oldest(struct student s[], int n);

请问是用 该如何写代码,我没有思路 是用 return 返回人的名字么?

结构体的使用,首先要定义:

#include<stdio.h>
struct student
{
    char name[10];
    int num;
    int age;
};//注意要分号

//然后就可以使用了:

void main()
{
    struct student s;
    struct student *p=&s;//指针指向,可以不用指针
    printf("input name:");
    gets(s.name);//若使用指针,则:gets(p->name);
    printf("input num:");
      scanf("%d",&s.num);//指针的写法:scanf("%d",&p->num);
    printf("input age:");
    scanf("%d",&s.age);
    
    //输出结果:
    printf("name\tnum\tage\t\n");
    printf("%s\t%d\t%d\n");
    
    
}

结构体类似于数组,但结构体能定义不同的数据类型,这也是它的特别之处

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-07
用flag表示年龄最大者在s中的位置,则可以使用return s[flag].name返回该人的姓名
第2个回答  推荐于2017-09-28
程序和例子如下。
比年龄,得序号 id, 返回 该 id 的 名字。
#include<stdio.h>
struct date{int year; int month; int day;};
struct student
{ char name[20]; struct date birth; };

char *oldest(struct student s[], int n){
int id=0;
int i;
for (i=1;i<n;i++){
if (s[i].birth.year < s[id].birth.year) id = i;continue;
if ((s[i].birth.year == s[id].birth.year) &&
(s[i].birth.month < s[id].birth.month) ) id = i;continue;
if ((s[i].birth.year == s[id].birth.year) &&
(s[i].birth.month == s[id].birth.month) &&
(s[i].birth.day < s[id].birth.day) ) id = i;continue;
}
return s[id].name;
}

main()
{
struct student s[4];
s[0].birth.year=1995;s[0].birth.month=5;s[0].birth.day=5;strcpy(s[0].name,"wang");
s[1].birth.year=1995;s[1].birth.month=5;s[1].birth.day=6;strcpy(s[1].name,"li");
s[2].birth.year=1994;s[2].birth.month=5;s[2].birth.day=7;strcpy(s[2].name,"wu");
s[3].birth.year=1996;s[3].birth.month=3;s[3].birth.day=5;strcpy(s[3].name,"zhao");
printf("%s",oldest(s, 4));
}追问

谢谢你的回答,不过有一点小问题,id = i;continue;
这里应该用上 {id = i;continue;}

本回答被提问者采纳
相似回答