Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: struct.

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 git diff: every line is new (+46).
--- /dev/null
+++ b/practice/10/cities.c
@@ -0,0 +1,46 @@
+ #include <assert.h>
+ #include <stdio.h>
+
+ #define MAX_NAME 20
+
+ /* City: three pieces of data of different types under one name. */
+ typedef struct {
+ char name[MAX_NAME];
+ int population;
+ double area; /* km2 */
+ } City;
+
+ /* Prints one city. Before: c != NULL. */
+ void print_city(const City *c) {
+ assert(c != NULL);
+ printf("%s: %d people, %.1f km2\n", c->name, c->population, c->area);
+ }
+
+ /* Gets a COPY of the city: the original doesn't change. */
+ void grow_copy(City c, int count) {
+ 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;
+ 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;
+ }