Passing Structs Example
Sample Program:
/* Short meaningless header comment that wouldn't get you a good
* grade on a project.
*/
#include
struct book {
char author[40];
char title[40];
int edition;
int callNumber;
float price;
};
struct inventory {
struct book current;
struct book replacement;
};
struct book GetBookInfo(void);
struct inventory GetInventoryInfo(void);
void PrintBook(struct book);
main() {
struct book new;
struct inventory fantasy;
printf("\nEnter the currently stocked book's information:\n");
fantasy = GetInventoryInfo();
PrintBook(fantasy.current);
printf("\nEnter the newly purchased book's information:\n");
new = GetBookInfo();
fantasy.replacement = new;
PrintBook(fantasy.replacement);
}
struct book GetBookInfo(void) {
struct book temp;
printf("Please enter the Name of the author: ");
scanf("%s", temp.author);
printf("Please enter the Title of the book: ");
scanf("%s", temp.title);
printf("Enter the book's Edition: ");
scanf("%d", &temp.edition);
printf("Enter its Call Number: ");
scanf("%d", &temp.callNumber);
printf("Enter the Price paid for the book: ");
scanf("%f", &temp.price);
return(temp);
}
struct inventory GetInventoryInfo(void) {
struct inventory temp;
temp.current = GetBookInfo();
return(temp);
}
void PrintBook(struct book out) {
printf("\nTitle:\t\t%s\n", out.title);
printf("Author:\t\t%s\n", out.author);
printf("Edition:\t%d\n", out.edition);
printf("Call Number:\t%d\n", out.callNumber);
printf("Price:\t\t%.2f\n\n", out.price);
return;
}
Output:
{2:58pm}[umbc7] cs201/dis5 >a.out
Enter the currently stocked book's information:
Please enter the Name of the author: McCaffery
Please enter the Title of the book: Dragonsong
Enter the book's Edition: 1
Enter its Call Number: 234
Enter the Price paid for the book: 5.99
Title: Dragonsong
Author: McCaffery
Edition: 1
Call Number: 234
Price: 5.99
Enter the newly purchased book's information:
Please enter the Name of the author: Lackey
Please enter the Title of the book: FireBird
Enter the book's Edition: 2
Enter its Call Number: 543
Enter the Price paid for the book: 6.99
Title: FireBird
Author: Lackey
Edition: 2
Call Number: 543
Price: 6.99
{2:59pm}[umbc7] cs201/dis5 >
Main Page
Last Modified 17 October 2000