C
stdlib.h
Learn functions like malloc, exit and atoi in stdlib.h.
stdlib.h
The <stdlib.h> header holds C's most-used general-purpose functions: memory allocation (malloc), program exit (exit), string-to-number conversion (atoi) and quick sort (qsort).
You saw malloc in earlier groups; now let's look at the other three. exit(1) terminates the program immediately; used on errors. atoi("42") converts a string to an integer and returns 42; characters that can't be converted yield 0. qsort sorts an array; it requires a comparison function. These functions are building blocks of C programs; nearly every real project uses them.
Using qsort
qsort is a general-purpose sort function. It can sort an array of any type; for that it asks for a comparison function.
Signature: void qsort(void *base, size_t count, size_t size, int (*cmp)(const void *, const void *)). base is the array start, count is the element count, size is the byte size of each element, cmp is the comparison function. The comparison function takes two const void * and returns negative, zero or positive. Example: int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; }. This sorts two integers ascending. Call: qsort(arr, 3, sizeof(int), cmp);. Now arr is sorted.
Exercise atoi and qsort
Write int cmp(const void *a, const void *b): return *(int*)a - *(int*)b;. In main do const char *s = "42";, int n = atoi(s);, int arr[] = {3, 1, 2};, qsort(arr, 3, sizeof(int), cmp);, printf("%d %d %d %d\n", n, arr[0], arr[1], arr[2]);.
Show example solution
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
int main(void) {
const char *s = "42";
int n = atoi(s);
int arr[] = {3, 1, 2};
qsort(arr, 3, sizeof(int), cmp);
printf("%d %d %d %d\n", n, arr[0], arr[1], arr[2]);
return 0;
}
Test yourself
-
What does atoi("42") return?
- 0 (error)
- "42" (string)
- 42 (integer)
- 42.0 (float)
Show answer
42 (integer) — atoi converts a string to an integer; "42" → 42.
-
stdlib functions
- malloc
- allocate memory
- exit
- leave program
- atoi
- string to number
- qsort
- sort array
-
The qsort call
qsort(arr, 3, sizeof(int), ____);
Show answer
qsort(arr, 3, sizeof(int), cmp);
Next lesson: string.h