Skip to content

Checkpoint: Records for Sessions

The Course
•
32 min study

Earlier today you grouped a session's label and duration into a struct Session and reached its fields with . on a variable and -> through a pointer. This checkpoint combines that record with the day's other pointer ideas, and adds no new syntax: a copy of a record is independent of the original, and a function that should change a record must receive its address, validate first and write only on success.

Predict and run

Predict before running C
#include <stdio.h>

struct Session {
    char label[16];
    int minutes;
};

int main(void) {
    struct Session original = {"C", 25};
    struct Session copy = original;
    copy.minutes = 40;
    printf("%s %d %d\n", original.label, original.minutes, copy.minutes);
    return 0;
}
Check your prediction
Text
C 25 40

Assigning a struct copies every field, including the whole label array. copy has its own 16 characters and its own minutes, so changing it left original alone. Set copy.label[0] = 'X'; and print both labels: only the copy changes. This is different from an array on its own, which cannot be assigned at all.

What you already have

  • struct Session from Update a Caller Safely: a char label[16] (at most 15 visible characters plus the terminator) and an int minutes.
  • . and ->. session.minutes on a struct variable; p->minutes through a pointer to one.
  • The output-parameter pattern. Return 1 or 0, check NULL and the value first, write through the pointer last.
  • Copies by value. As the predict step showed, passing a struct Session (not a pointer) gives the function its own copy, which is useful for read-only work and useless for updates.

Plan before you type

  1. Write the expected record after each call: setting 40 succeeds, setting 0 fails, adding 150 to 40 fails because 190 is over the limit, adding 20 succeeds.
  2. Write set_duration with one guard: NULL record or a value outside 1 through 180 returns 0.
  3. Assert a successful change, then a rejected one, and check the field after each.
  4. Write add_minutes, which must check the resulting duration, not just the extra amount.
  5. Print the final record from a function that takes the record by value.
Prove it can fail

When every assertion passes, break add_minutes on purpose: store updated into session->minutes before calling set_duration. The rejected +150 now leaves the record at 190, so the assertion after it fails, although the call still returned 0. Restore it.

Passing the record by value is the other classic slip, but it is not a one-word change: a struct Session can never be NULL, so the guard no longer compiles, and every call that passes &session is rejected too. The playground below is the by-value version with those parts already removed. It compiles, and it reports success.

Success on a copy C
#include <stdio.h>

struct Session {
    char label[16];
    int minutes;
};

/* Broken on purpose: the record arrives by value. */
int set_duration(struct Session session, int minutes) {
    if (minutes < 1 || minutes > 180) {
        return 0;
    }
    session.minutes = minutes;
    return 1;
}

int main(void) {
    struct Session today = {"C", 25};
    int ok = set_duration(today, 40);
    printf("returned %d, minutes %d\n", ok, today.minutes);
    return 0;
}
Text
returned 1, minutes 25

set_duration validated 40, stored it and returned 1, all correctly, but into its own copy, which vanished when it returned. The caller's today still says 25. A test that checked only the return value would pass; the assertion on the field is what catches it.

Mistakes worth checking for

  • The function reports success but the record is unchanged. It received the struct by value and changed a copy. Pass &session and use ->.
  • member reference type is a pointer; did you mean to use '->'? You wrote session.minutes on a pointer. Use session->minutes.
  • A rejected update still changes the record. The store happens before, or between, the checks.
  • add_minutes accepts 40 plus 150. It validated extra against 180 instead of the new total session->minutes + extra.
  • The label prints extra characters. The text was written without its terminator, or longer than 15 characters. Use a string initializer or snprintf with sizeof.

Practice

Exercise

Your turn

Write int set_duration(struct Session *session, int minutes) and int add_minutes(struct Session *session, int extra). Both reject a NULL record and any result outside 1 through 180, return 0 and leave the record unchanged; on success they update minutes and return 1. Write void print_session(struct Session session) too. Starting from {"C", 25}, set 40, try to set 0, try to add 150, add 20, assert each result and print:

Text
C: 60 minutes
Record checks passed
Your workspace C
#include <stdio.h>
#include <assert.h>

struct Session {
    char label[16];
    int minutes;
};

int main(void) {
    struct Session session = {"C", 25};
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Apply the output-parameter pattern to a field. For add_minutes, compute the new total in a local variable first and validate that, then store it.

Hint 2: a first step

In add_minutes, check for NULL before you read session->minutes. Then compute int updated = session->minutes + extra; and reuse the same range check as set_duration.

Show one solution
C
#include <stdio.h>
#include <assert.h>

struct Session {
    char label[16];
    int minutes;
};

int set_duration(struct Session *session, int minutes) {
    if (session == NULL || minutes < 1 || minutes > 180) {
        return 0;
    }
    session->minutes = minutes;
    return 1;
}

int add_minutes(struct Session *session, int extra) {
    if (session == NULL) {
        return 0;
    }
    int updated = session->minutes + extra;
    return set_duration(session, updated);
}

void print_session(struct Session session) {
    printf("%s: %d minutes\n", session.label, session.minutes);
}

int main(void) {
    struct Session session = {"C", 25};
    int ok = set_duration(&session, 40);
    assert(ok && session.minutes == 40);
    ok = set_duration(&session, 0);
    assert(!ok && session.minutes == 40);
    ok = add_minutes(&session, 150);
    assert(!ok && session.minutes == 40);
    ok = add_minutes(&session, 20);
    assert(ok && session.minutes == 60);
    ok = add_minutes(NULL, 5);
    assert(!ok);
    print_session(session);
    printf("Record checks passed\n");
    return 0;
}
Text
C: 60 minutes
Record checks passed

add_minutes reuses set_duration, so the range rule lives in one place and the record is written in exactly one line of the program. The NULL check comes before the first ->, because reading a field through a null pointer is undefined. Each update runs in its own statement and assert checks the saved ok, so the updates would still happen in a build that defines NDEBUG (Day 3). print_session takes a copy, which is fine for reading a small record. Tomorrow you will read durations from real input and store records in a fixed-capacity collection.

Was this article helpful?

Your response is saved on this device.