Struct with Nested Member in C

Level 5253 keystrokes

Defines an Address struct and a Person struct that contains an Address as a member, initializes both with nested braces and reaches the inner fields with chained dots such as p.addr.city. It prints Alice, Tokyo and 12345.

C code

// The inner structure: an address
1struct Address {
// City name, up to 19 characters plus '\0'
2 char city[20];
// Postal code stored as an int
3 int zipcode;
4};
5
// The outer structure: a person
6struct Person {
// The person's name
7 char name[20];
// A whole Address struct embedded as a member (not a pointer)
8 struct Address addr;
9};
10
// The inner braces initialize the nested addr member
11struct Person p = {"Alice", {"Tokyo", 12345}};
// A top-level member: prints Name: Alice
12printf("Name: %s\n", p.name);
// Two dots reach the nested field: prints City: Tokyo
13printf("City: %s\n", p.addr.city);
// Prints Zip: 12345
14printf("Zip: %d\n", p.addr.zipcode);

Output

Name: Alice
City: Tokyo
Zip: 12345
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 10
  • "× 10
  • ,× 5
  • .× 5
  • {× 4
  • }× 4
  • :× 3
  • (× 3
  • )× 3
  • \× 3

More C examples at level 5

← C typing practice