NULL
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
NULL is a special pointer value: "points to nothing". Functions return it when something didn't work out or nothing was found:
malloc— if there's no memory;fopen— if the file didn't open;strchr(s, 'x')— if the character isn't in the string;- your own search functions — if the item wasn't found.
Dereferencing NULL (*p, p->x) is undefined behaviour; in practice the program crashes with a Segmentation fault. That's why a pointer is checked before it's used:
char *dot = strchr(filename, '.');
if (dot != NULL)
printf("extension: %s\n", dot + 1);
else
printf("no extension\n");
if (p) and if (p != NULL) are the same thing: NULL is false.
The inventor of NULL, Tony Hoare, called it his "billion-dollar mistake": over the decades, forgotten checks have cost the industry dearly.
Task. Write int *find(int *a, int n, int target), which returns a pointer to the first item equal to target, or NULL. The program reads an array and a number, and prints the index of the item found (using a pointer difference) or not found.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.