Members
A member of a structure works like an ordinary variable: you can read it, calculate with it and change it. You only have to say whose member it is. bread.count is the count of the bread, not of the milk. This program changes the members of the bread and calculates with them:
#include <stdio.h>
#include <string.h>
struct product {
char name[20];
double price;
int count;
};
int main(void) {
struct product bread = {"Bread", 32.5, 2};
bread.count = 3;
bread.price -= 2.5;
printf("%s: %d x %.2f = %.2f\n", bread.name, bread.count, bread.price, bread.count * bread.price);
strcpy(bread.name, "Rolls");
printf("%s: %d x %.2f\n", bread.name, bread.count, bread.price);
return 0;
}This prints:
Bread: 3 x 30.00 = 90.00
Rolls: 3 x 30.00bread.count = 3; stores a new value in the member count, and bread.price -= 2.5; lowers the price by 2.5. The other members stay as they were. Everything you know about variables works with members too: +=, ++, or a condition such as if (bread.count > 0).
A text member is different, because it is an array, and you can't assign to an array with =. If you write bread.name = "Rolls"; instead of the strcpy line, the program doesn't compile:
main.c:16:16: error: array type 'char[20]' is not assignable
16 | bread.name = "Rolls";
| ~~~~~~~~~~ ^That's why the program copies the text in with strcpy from string.h, as you would into any string. The array must have room for the new text and for the '\0' at its end: char name[20] has room for up to 19 characters.
Also watch out for typos in the names of members. The compiler knows only the members from the definition, so bread.prize ends with an error that says the structure has no such member:
main.c:17:62: error: no member named 'prize' in 'struct product'
17 | printf("%s: %d x %.2f\n", bread.name, bread.count, bread.prize);
| ~~~~~ ^Instructions
The hero of a game fights a dragon. In place of the comment, lower hero.health by 35 with -= and raise hero.level by one. Below that, print the hero again with the same printf as above. The program prints Zara: level 1, health 100 and below it Zara: level 2, health 65.
For defeating the dragon, the hero gets a new name. At the end of main (before return 0;), copy the text Zara the Brave into hero.name with strcpy (add #include <string.h> at the top) and print the hero once more. The last line is Zara the Brave: level 2, health 65.
Start programming for free
2/9