CodeBlanks Logo Icon CodeBlanks

stdlib.h

  • C course
  • Intermediate
  • Lesson 82/116
  • 4 min

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.

Practice 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]);.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>

// cmp: compare two ints (for qsort)
// main: convert "42" to int with atoi
// sort {3, 1, 2} with qsort
// print n and the sorted array with printf

int main(void) {
    // write here
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

42 1 2 3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does atoi("42") return?

  • 0 (error)
  • "42" (string)
  • 42 (integer) Correct answer
  • 42.0 (float)

Explanation: atoi converts a string to an integer; "42" → 42.

2 stdlib functions

Term Meaning
malloc allocate memory
exit leave program
atoi string to number
qsort sort array

3 The qsort call

Question
qsort(arr, 3, sizeof(int), ____);
Answer
qsort(arr, 3, sizeof(int), cmp);

Explanation: qsort's last parameter is the comparison function.

All lessons in Intermediate