Skip to the task
Layout
Back to classic view

You are looking at lesson 10. Your place is still lesson 3, task 1: Conditions.

CREATETask 4 of 17 · step 3: The City structureThe City structure
The City structure in practice/10/

typedef struct City, print_city through a const pointer, grow_copy and grow – a copy versus a pointer.

Checklist

  • Every task is one commit with a clear message.
  • Zero compiler warnings: the code builds with -Werror.
  • Once per topic you step through your code in the debugger (CLion, gdb).
  • Every function has preconditions and postconditions, and assert tests check them.
  • A multi-file program: .h files with Doxygen comments and their own CMake target.
  • Input only through the safe functions of your own input.h.

Numbered notes in the code explain the important lines.

Details & hint
  • City vilnius = {.name = "Vilnius", ...} – members by name, the order doesn't matter.
  • c->population is the same as (*c).population.
  • City copy = kaunas; copies the whole structure, the array inside too.
practice 10 cities.c Code Diff +46
A · NEW FILE Create this file. Every line is new: see the green bar.
#include <assert.h>
#include <stdio.h>
#define MAX_NAME 20
/* City: three pieces of data of different types under one name. */
typedef struct {
Note 1: A new type made of several members.
char name[MAX_NAME];
int population;
double area; /* km2 */
} City;
Note 2: The typedef name: from here on, City x;
/* Prints one city. Before: c != NULL. */
void print_city(const City *c) {
Note 3: A const pointer: fast and read-only.
assert(c != NULL);
printf("%s: %d people, %.1f km2\n", c->name, c->population, c->area);
Note 4: -> is a member through a pointer.
}
/* Gets a COPY of the city: the original doesn't change. */
void grow_copy(City c, int count) {
Note 5: Gets a copy: the original won't change.
c.population += count;
}
/* Gets a pointer to the city: changes the original. Before: c != NULL. */
void grow(City *c, int count) {
assert(c != NULL);
c->population += count;
}
int main(void) {
City kaunas = {"Kaunas", 300000, 157.0};
City vilnius = {.name = "Vilnius", .population = 600000, .area = 401.0};
print_city(&kaunas);
print_city(&vilnius);
printf("sizeof(City): %zu\n", sizeof(City));
City copy = kaunas;
Note 6: = copies the whole structure.
copy.population = 0;
printf("kaunas: %d, copy: %d\n", kaunas.population, copy.population);
grow_copy(kaunas, 1000);
printf("After grow_copy: %d\n", kaunas.population);
grow(&kaunas, 1000);
printf("After grow: %d\n", kaunas.population);
return 0;
}