Back to main

Lab 6 for C programming

Exercises:

Exercise 14: Pointers

Background

Pointers: stuff from lecture notes.


To keep track of time, computers need something to measure it against. In C on the lab computers, we get the number of seconds since 00:00:00 UTC on 1 January 1970.

As you might imagine, this produces a fairly large number -- it exceeds the bounds of a normal int. We therefore use a long int, which has twice the number of bits of a normal int. Our time.h library also defines a special data type to store the time value: time_t. On our computers, this is the same as a long int.

Technical details

Swapping data with pointers:

#include <stdio.h>

void swap(int *px, int *py) {
    int temp = *px;
    *px = *py;
    *py = temp;
}

int main() {
    int x = 1;
    int y = 2;
    printf("initial: %i %i\n", x, y);
    swap( &x, &y);
    printf("swapped: %i %i\n", x, y);
}
Watch out for the * and &

Getting the time:

#include <stdio.h>
#include <time.h>  // extra include

int main() {
    time_t now;
    now = time(NULL);

    long int a = now;
    printf("%li\n", now);
}

Your task...

Calling time(NULL) gives you a large integer. Use this value to calculate today's year, date, hours, and minutes.


(optional: handle leap-years correctly, and print the month as well)

... show your work to a demonstrator

Back to main


Creative Commons LicenseUnless otherwise noted, all materials on these pages are licenced under a Creative Commons Licence.