The Null Pointer
Sometimes a pointer has nothing to point to. Imagine a function that searches an array of temperatures for the first frost, a temperature below zero, and returns its address. What should it return when there was no frost all week? For this, C has the value NULL, the null pointer: a pointer that points nowhere.
This function returns an address, so its return type is int *. &numbers[i] is the address of the element with the index i:
int *find_negative(int *numbers, int count) {
for (int i = 0; i < count; i++) {
if (numbers[i] < 0) {
return &numbers[i];
}
}
return NULL;
}Why does it return an address and not the temperature itself? Because a number can't say "there is none": any number the function returned could be a real temperature. A pointer can, because NULL is not the address of any variable.
Before you use a pointer that can be NULL, check it with if:
#include <stdio.h>
int *find_negative(int *numbers, int count) {
for (int i = 0; i < count; i++) {
if (numbers[i] < 0) {
return &numbers[i];
}
}
return NULL;
}
int main(void) {
int week[] = {3, 1, -2, 0, -4};
int *frost = find_negative(week, 5);
if (frost != NULL) {
printf("First frost: %d\n", *frost);
} else {
printf("No frost\n");
}
return 0;
}This prints:
First frost: -2Why check? Reading or writing through NULL is a bug, because there is no variable there. On a computer, such a program usually crashes, often with the message Segmentation fault. Here in the browser, reading through NULL stops the program with the error RuntimeError: unreachable, the same error as for an index past the end of an array. It doesn't say what went wrong, so when you see it in a program with pointers, look for a pointer that can be NULL.
NULL is also a good starting value for a pointer that has nothing to point to yet: int *found = NULL;. A pointer without any value, int *p;, is a compile error here as soon as you use it (variable 'p' is uninitialized when used here), like any variable without a value.
One more rule for functions that return a pointer: return only addresses of things that still exist when the function ends, such as the elements of the array it got. A function's local variables disappear when it ends, so never return their addresses.
Instructions
In the array row, 1 is a taken seat and 0 a free one. The program doesn't compile: when no seat is free, the function find_free_seat ends without return. Add return NULL; at its end, after the loop. The program then prints Booked twice.
A third person comes to the cinema. In main, call book_seat(row, 4); a third time. The program prints Booked twice and then stops with RuntimeError: unreachable: the row is full, so find_free_seat returned NULL, and book_seat tried to write through it. Fix book_seat: when seat is NULL, it prints Sold out and changes nothing; otherwise, it books the seat as before. The program prints Booked, Booked and Sold out.
Start programming for free
9/11