C Exercise 78
100 Classic C Language Examples
**Problem:** Find the oldest person and output it. Please find out what is wrong with the program.
**Analysis:** None.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
#include
<
stdio.h
#include
<
stdlib.h// Define a struct type to store a person's name and age
struct
man
{
char
name
[
20
]
;
int
age
;
}
person
[
3
]
=
{
{
"
li
"
,
18
}
,
{
"
wang
"
,
25
}
,
{
"
sun
"
,
22
}
}
;
// Initialize the array
int
main
(
)
{
struct
man
q
=
NULL
;
// Used to point to the oldest person
struct
man
p
=
person
;
// Point to the starting address of the array
int
i
;
int
max_age
=
0
;
// Store the maximum age
// Traverse the array to find the oldest person
for
(
i
=
0
;
i
<
3
;
i
++
)
{
if
(
p
->
age
max_age
)
{
// If the current age is greater than max_age
max_age
=
p
->
age
;
// Update max_age
q
=
p
;
// Point q to the current person
}
p
++;
// Move to the next person
}
// Output the name and age of the oldest person
if
(
q
!=
NULL
)
{
printf
(
"
%s %d
\
n
"
,
q
->
name
,
q
->
age
)
;
}
else
{
printf
(
"
No person information found.
\
n
"
)
;
}
return
0
;
}
The above example produces the following output:
wang 25