Week 09 Tutorial Sample Answers

Part 0: Welcome, Assignment 1 & Assignment 2

Great job getting through Assignment 1!

Assignment 2 will be released late this week!

Part 1: Functions and Pointers

Have a quick look at the following code:

#include <stdio.h>

void halve_values(int num_1, int num_2, int num_3);

int main(void) {
    int num_1 = 4;
    int num_2 = 10;
    int num_3 = 16;

    printf("Values before halved:\n");
    printf("Num 1: %d\n", num_1);
    printf("Num 2: %d\n", num_2);
    printf("Num 3: %d\n", num_3);

    halve_values(num_1, num_2, num_3);

    printf("Values after halved:\n");
    printf("Num 1: %d\n", num_1);
    printf("Num 2: %d\n", num_2);
    printf("Num 3: %d\n", num_3);

    return 0;
}

void halve_values(int num_1, int num_2, int num_3) {
    num_1 = num_1 / 2;
    num_2 = num_2 / 2;
    num_3 = num_3 / 2;
}

Note that function halve_values doesn't seem to be working correctly.

Fixing the program

Use your knowledge of how to work with pointers to fix the program.

The following diagram may be useful as a guide for explaining how pointers work in functions: Pointers in Function

Part 2: Struct pointers

Have a quick look at the following code which contains a struct book.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct book {
    char title[100];
    char author[100];
    int year;
};

void modify_book(struct book book);

int main(void) {
    struct book book;

    strcpy(book.title, "To Kill a Mockingbird");
    strcpy(book.author, "Harper Lee");
    book.year = 1960;

    printf("Before modification:\n");
    printf("Title: %s, Author: %s, Year: %d\n", book.title, book.author, book.year);

    modify_book(book);

    printf("After modification:\n");
    printf("Title: %s, Author: %s, Year: %d\n", book.title, book.author, book.year);

    return 0;
}

void modify_book(struct book book) {
    book.year = 1925;
    strcpy(book.title, "The Great Gatsby");
    strcpy(book.author, "F. Scott Fitzgerald");
}

Note that function modify_book in this example doesn't seem to be working correctly.

Part 3: Malloc and free

In this section we'll visit malloc and free.

Group activity

Using your knowledge of malloc() and sizeof(), write up code to malloc the following:

struct my_struct {
    int number;
    char letter;
    double another_number;
}

Voice of the Student

✨ Help Us Improve Your Learning Experience ✨

Your feedback helps us understand what’s working well and what might need improvement. This quick, anonymous check-in has just two questions and takes less than a minute to complete.

Please answer honestly — your input makes a real difference.