- How to define a
structwith two string members and one floating-point member - Why each string needs its own
char[]array with a distinct length (100 for title, 50 for author) - Why strings must be assigned with
strcpyand not= - How to format a price with
%.2fto show exactly two decimal places - Why the
floatprice should bedoublein modern code for extra precision
Modelling a Book
A book is a composite object: it has a title, an author, and a price. Each is a different type — the title and author are strings, the price is a number. This is exactly the kind of entity structures are designed for. Before structures, you'd have to declare three separate variables: char title[100];, char author[50];, float price; — and if you had ten books, you'd need 30 variables. With a struct, you have struct book b1, b2, ..., b10; and each one is a self-contained record.
The most interesting design decision here is how long to make each string array. The title can be long — some titles run to 200 characters or more — so 100 is a reasonable default. The author name is usually shorter — 50 characters is enough for even the longest author names. The price is a float (or double) because books are priced with cents, and integer cents would require extra arithmetic on every computation. These choices matter because they determine how much memory each book consumes and how likely the program is to truncate input or overflow a buffer.
The rest of the program is the familiar pattern: define the struct, declare a variable, assign each member, print each member. This assignment is intentionally similar to the student-structure assignment — the goal is to see that the pattern is the same regardless of what entity you're modelling. Once you understand struct book, struct student, and struct point, you can model any record in any domain: invoices, employees, appointments, products, whatever your program needs.
💡 In one line: struct book { char title[100]; char author[50]; float price; }; defines a new type; struct book b; creates one book; strcpy(b.title, "…") sets the title.
The Structure Blueprint
A struct definition is a blueprint — no memory is allocated until you declare a variable. The definition says "whenever I ask for a struct book, reserve 100 bytes for the title, 50 for the author, and 4 for the price."
struct book {
char title[100];
char author[50];
float price;
}; /* <-- the semicolon is REQUIRED */
Three things to notice. First, the title array is 100 characters — enough for most titles, though not all. Second, the author array is 50 characters — smaller because author names are usually shorter. Third, the price is a float — 4 bytes, about 7 significant decimal digits, which is enough for prices up to a few million with 2 decimal places. For more precision, use double; for currency, use integer cents and avoid floats entirely.
| Member | Type | Purpose | How to assign |
|---|---|---|---|
title | char[100] | Book's title | strcpy(b.title, "The C Programming Language") |
author | char[50] | Author's name | strcpy(b.author, "Kernighan & Ritchie") |
price | float | Price in your currency | b.price = 45.99 |
The sizeof(struct book) on a typical 64-bit system is 156 bytes — 100 + 50 + 4 = 154, plus 2 bytes of padding for alignment. The padding depends on the member order and the platform's alignment rules. Never hardcode the size; always use sizeof.
Complete C Program
Program: define a book structure and print one record
#include <stdio.h>
#include <string.h>
struct book {
char title[100];
char author[50];
float price;
};
int main(void) {
struct book b;
/* Assign values to the members */
strcpy(b.title, "The C Programming Language");
strcpy(b.author, "Kernighan & Ritchie");
b.price = 45.99f;
/* Print the record */
printf("Book Record\n");
printf("-----------\n");
printf("Title : %s\n", b.title);
printf("Author : %s\n", b.author);
printf("Price : %.2f\n", b.price);
return 0;
}
And here's a variant that reads the record from the user with scanf, which is how you'd use it in a real program:
Variant: read book data from the user
#include <stdio.h>
#include <string.h>
struct book {
char title[100];
char author[50];
float price;
};
int main(void) {
struct book b;
printf("Enter title: ");
scanf(" %99[^\n]", b.title); /* read up to 99 chars, stop at newline */
printf("Enter author: ");
scanf(" %49[^\n]", b.author); /* read up to 49 chars, stop at newline */
printf("Enter price: ");
scanf("%f", &b.price);
printf("\nBook Record\n");
printf("-----------\n");
printf("Title : %s\n", b.title);
printf("Author : %s\n", b.author);
printf("Price : %.2f\n", b.price);
return 0;
}
The first version is the assignment answer — it demonstrates the struct, the members, and how to print them. The second version is what you'd actually write in a real program: it reads the record from the user. The " %99[^\n]" and " %49[^\n]" formats are scanf idioms for reading whole lines (including spaces) into char arrays, with the length cap preventing overflow. The leading space in each format skips any leftover newline from the previous scanf, which is essential when reading two lines in succession.
Program Output
Book Record
-----------
Title : The C Programming Language
Author : Kernighan & Ritchie
Price : 45.99
And for the read-from-user variant:
Enter title: The C Programming Language
Enter author: Kernighan & Ritchie
Enter price: 45.99
Book Record
-----------
Title : The C Programming Language
Author : Kernighan & Ritchie
Price : 45.99
Try changing the values and re-running — the output should change to match. Try a title with spaces and see how the %99[^\n] format captures it correctly. Try entering a price with more decimals like 45.999 and observe that %.2f rounds it to 46.00.
Step-by-Step Explanation
Let's walk through the program piece by piece.
1. The struct definition (outside main)
struct book { char title[100]; char author[50]; float price; }; sits outside main, which means every function in the file can use the type. The three members are: title (a 100-char array), author (a 50-char array), and price (a float). The semicolon after the closing brace is required — omitting it produces the classic "expected ';' after struct definition" error.
2. Declaring a variable
struct book b; declares a variable named b of type struct book. On a typical 64-bit system, b occupies 156 bytes — 100 for the title, 50 for the author, 4 for the price, and 2 bytes of padding. Unlike the definition, this declaration actually allocates memory, and b is a single variable holding all three fields.
3. Assigning members
The dot operator (.) accesses a member of a struct variable: b.title, b.author, b.price. For the two string members, we use strcpy — you can't write b.title = "The C Programming Language" because array names in C are not assignable. For price, a direct assignment works: b.price = 45.99f;. The f suffix on the literal ensures it's a float, not a double — though in this context C will convert a double literal to float implicitly, with a warning in some compilers.
4. Printing the record
Each printf pulls out one member: %s for the strings, %.2f for the price with exactly two decimal places. The formatting isn't required by the assignment, but it separates "works" from "works well" — a well-formatted price reads as 45.99, not 45.990000.
5. Why two separate string arrays
The title and author are separate members — each has its own char[] buffer. You could theoretically use one combined string ("Kernighan & Ritchie: The C Programming Language"), but then you couldn't search by author or by title separately. The whole point of a struct is to keep semantically distinct fields as distinct members. Separating them also lets you size each array appropriately — 100 for titles, 50 for authors — instead of paying for a single one-size-fits-all buffer.
6. Precision and the price type
A float has about 7 significant decimal digits — enough to represent prices up to 99999.99 exactly. For typical book prices, that's plenty. But for financial computations (totals, taxes, percentages), floating-point rounding errors can accumulate. Serious financial software uses integer cents (or a decimal type) instead of float. For this assignment, float is fine; for a real bookstore system, you'd likely use long long cents or a decimal library.
7. Why the struct is defined outside main
Defining it inside main works for a single-function program, but defining it at file scope makes it available to every function in the file. Once you add printBook(), readBook(), and compareBooks(), each function needs to know the type. File-scope definition is the idiomatic C style — the same pattern you'll use for every structure in this series.
🎯 Remember this: struct book { ... }; is a type definition (semicolon required). Two string members need separate char[] buffers. Use strcpy for string members — = doesn't work for arrays. Print prices with %.2f for two decimal places.
Frequently Asked Questions
1. Why do the title and author each need their own char[] array?
Because they're separate logical fields — the title is not part of the author, and the author is not part of the title. If you combined them into one string, you couldn't search by author or by title separately, you couldn't display them in different parts of a UI, and you couldn't easily format them differently. Each field of a struct should correspond to a semantically distinct piece of data.
2. Why is the title array 100 and the author array 50?
Because titles are typically longer than author names. Some book titles run to 200 characters or more, but 100 covers the vast majority of books. Author names almost never exceed 50 characters. These sizes are a trade-off: larger arrays waste memory per book, smaller arrays risk truncation of long titles or names. In a production system, you might use dynamic allocation (malloc) to store exactly the needed length. For a teaching example, fixed sizes are fine.
3. Why can't I write b.title = "The C Programming Language"?
Because title is a char array, and array names in C are not assignable. You must use strcpy(b.title, "The C Programming Language") to copy each character into the array. The only place an initializer list can set the array is at the point of declaration: struct book b = {"The C Programming Language", "Kernighan & Ritchie", 45.99}; works, but a subsequent assignment doesn't.
4. Why does the price print as 45.99 with %.2f but 45.990000 with %f?
Because %f without a precision specifier defaults to 6 decimal places, showing all the visible digits of the underlying float. %.2f tells printf to show exactly 2 decimal places, rounding if necessary. Since prices are conventionally shown with 2 decimals (the currency's minor unit), %.2f is the right choice. In a real system, you'd also handle currency formatting properly with locale-aware functions.
5. Should the price be a float or a double or an int?
For a teaching example, float is fine. For a production system, double is slightly better (more precision, negligible size difference). But for financial software, neither — floating-point types can't represent most decimal fractions exactly, leading to rounding errors when summing many prices. Use integer cents instead (long long price_cents), or a decimal library like GMP's mpq. The convention is to compute in cents and format for display.
6. Can I use typedef to shorten the type name?
Yes: typedef struct book { char title[100]; ... } Book; lets you write Book b; instead of struct book b;. This is common in modern C code and especially useful when you have many structures — no struct keyword every time. For this assignment, the plain struct book is fine, but feel free to use typedef in your own versions. We'll see more of it in later assignments.
💡 Tip: After this program, try adding an int pages member and a char isbn[14] member (13 digits plus a null terminator). You'll see how the struct grows. Then try making an array of books: struct book library[10]; — that's the foundation of assignment 6 (total price of a collection of books), which extends this pattern to arrays.