Solution for Exercise 14-8
ex1408
#include <stdio.h>
#include <string.h>
int main()
{
struct date
{
int month;
int day;
int year;
};
struct human
{
char name[45];
struct date birthday;
};
struct human president;
strcpy(president.name,"George Washington");
president.birthday.month = 2;
president.birthday.day = 22;
president.birthday.year = 1732;
printf("%s was born on %d/%d/%d\n",
president.name,
president.birthday.month,
president.birthday.day,
president.birthday.year);
return(0);
}
Notes
* To reference a structure within a structure, you use two dots in the variable name, as shown in the solution for Exercise 14-8. president.brithday is a member in a structure, but that member is also a structure. Therefore you need to use two dots to get at the inside member's variables, president.birthday.day.
* Line 19 uses the strcpy() function to fill the president.name variable. Remember, you use strcpy() to copy string data, not the equal sign. Refer to Chapter 13 in the book.
* The date type of structure, such as the one shown above, is one of the most common to include within another structure.
* As discussed in the solution for Lesson 14-5, you can declare the structure's contents in the code, which may save some time. The method for declaring a structure within a structure involves a bonus set of curly brackets. This type of declaration for Exercise 14-8 might look like this:
struct date
{
int month;
int day;
int year;
};
struct human
{
char name[45];
struct date birthday;
} president = {
"George Washington", { 2, 22, 1732 }
};
The birthday structure is included in the declaration in curly brackets. If you forget to include them, the compiler issues a warning. The code may still run, but I recommend keeping that internal structure's members in curly brackets as shown above.
Copyright © 1997-2025 by QPBC.
All rights reserved
