/* Kelly & Pohl Exercise 12.1, p. 424 */ /* */ /* Lone Leth Thomsen, 11. April 2003 */ #include <string.h> #include <stdio.h> struct food { char name[15]; int portion_weight; int calories; }; struct food meal[10]; int main(int argc, char* argv[]) { meal[0].name[0] = 'a'; meal[0].name[1] = 'p'; meal[0].name[2] = 'p'; meal[0].name[3] = 'l'; meal[0].name[4] = 'e'; meal[0].name[5] = '\0'; meal[0].portion_weight = 4; meal[0].calories = 200; return 0; }
![]() | struct food { char name[15]; int portion_weight; int calories; }; |
define the structure food with members name, portion_weight and calories. The tag name of this structure is food. |
![]() | struct food meal[10]; |
declares an array meal[10] of this structure. |
![]() | meal[0].name[0] = 'a'; meal[0].name[1] = 'p'; meal[0].name[2] = 'p'; meal[0].name[3] = 'l'; meal[0].name[4] = 'e'; meal[0].name[5] = '\0'; meal[0].portion_weight = 4; meal[0].calories = 200; |
assign values to the three members of meal[0]. The name is divided into individual characters, including the end-of-string character '\0'. We might, as well assign meal[0].name to "apple". However, in order to do that when name is declared as char name[15], we will have to do strcpy(name,"apple"). |