struct bookInfo * books[3]; // Array of three structure variables
// Get the information about each book from the user
for (ctr = 0; ctr < 3; ctr++)
{
books[ctr] = (struct bookInfo*)malloc(sizeof
(struct bookInfo));
printf("What is the name of the book #%d?\n", (ctr+1));
gets(books[ctr]->title);
puts("Who is the author? ");
gets(books[ctr]->author);
puts("How much did the book cost? ");
scanf(" $%f", &books[ctr]->price);
puts("How many pages in the book? ");
scanf(" %d", &books[ctr]->pages);
getchar(); //Clears newline input to keep things clean for
// next round
}
// Print a header line and then loop through and print the info
printf("\n\nHere is the collection of books: \n");
for (ctr = 0; ctr < 3; ctr++)
{
printf("#%d: %s by %s", (ctr+1), books[ctr]->title,
books[ctr]->author);
printf("\nIt is %d pages and costs $%.2f", books[ctr]->pages,
books[ctr]->price);
printf("\n\n");
}
return(0);
}
The Absolute Minimum
This chapter’s goal was to teach you about structures. A structure is an aggregate
variable data type. Whereas an array must hold values that are all the same data type, a
structure can hold several values of different data types.
Before using a structure variable, you must tell C exactly what the structure looks like
with a struct statement. The struct statement lets C know how many members
are in the structure and the data types of each member. A structure variable is like a
group of more than one variable of different data types. Key concepts in this chapter
include:
- Define structures when you want to group items of different data types.
- Declare a structure before defining a structure variable.
- Use the dot operator to access individual data members within a structure variable.
- Use the -> (the structure pointer operator) to access individual data members
within a structure pointed to by a pointer variable. - Don’t use member names as variables. Member names exist only so you can work
with an individual part of a structure.