BETA Try the new lesson view
Code

The City structure

The first program with a structure: Lithuanian cities. The population figures are rounded – what matters here isn't them but how you work with them.

Create practice/10:

add_executable(p10_cities cities.c)

cities.c:

  • typedef struct { ... } City; – name, population and area in km².
  • void print_city(const City *c) – one city on one line, through ->.
  • grow_copy(City c, ...) and grow(City *c, ...) – the same operation on a copy and through a pointer.
  • main: two cities (one in member order, the other with names), sizeof(City), a copy made with = and both grow calls side by side.

Run it

p10_cities and ▶:

Kaunas: 300000 people, 157.0 km2
Vilnius: 600000 people, 401.0 km2
sizeof(City): 32
kaunas: 300000, copy: 0
After grow_copy: 300000
After grow:      301000
  • copy.population = 0 didn't change kaunas: = made a separate copy.
  • grow_copy grew its own copy and threw it away. grow got the address and changed kaunas itself.

A structure in the debugger

A breakpoint at grow(&kaunas, 1000);, Debug. In the Variables window expand kaunas: three members with their values. F7 steps into grow: there c is a pointer, and expanding it shows the same members. F8, and population changes in the window.

Commit: Add City structure.