Summary - Standard library
- C course
- Intermediate
- Lesson 87/116
- 5 min
Combine stdlib, math and time to write a timing app.
Summary - Standard library
In this group we toured five headers of the C standard library: stdlib.h (atoi, qsort), string.h (strcpy, strcat, strlen), math.h (sqrt, pow), time.h (struct tm, mktime) and ctype.h (toupper).
Mini task: sort {3, 1, 2} with qsort, uppercase "test" with toupper, get its length with strlen and print all in one printf. This shows the power of the standard library: sorting, string editing and length computation in a few lines. Output: 1 2 3 TEST 4. Here 4 is the character count of "TEST" excluding null.
Practice Combine five headers
Write int cmp(const void *a, const void *b): return *(int*)a - *(int*)b;. In main do int arr[] = {3, 1, 2};, qsort(arr, 3, sizeof(int), cmp);. char s[] = "test";, for (int i = 0; s[i]; i++) s[i] = toupper(s[i]);. printf("%d %d %d %s %zu\n", arr[0], arr[1], arr[2], s, strlen(s));.
Starter code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// cmp: compare two ints
// main: sort {3, 1, 2} with qsort
// uppercase "test" with toupper
// print sorted array, uppercased string and length with printf
int main(void) {
// write here
return 0;
}Sample solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int cmp(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
int main(void) {
int arr[] = {3, 1, 2};
qsort(arr, 3, sizeof(int), cmp);
char s[] = "test";
for (int i = 0; s[i]; i++) s[i] = toupper(s[i]);
printf("%d %d %d %s %zu\n", arr[0], arr[1], arr[2], s, strlen(s));
return 0;
}Expected output
1 2 3 TEST 4
Care with the standard library
The standard library is powerful but needs care. Three key points: check memory bounds (strcpy/strcat overflow), mind type compatibility (atoi can't signal errors, returns 0), know your locale (toupper by default only handles ASCII letters).
strncpy and strncat are safer bounded variants; they take a size parameter. strtol is more robust than atoi; it signals errors via a separate pointer. toupper for non-ASCII letters needs setlocale(LC_ALL, "tr_TR"); otherwise 'i' becomes 'I' (when it should become 'İ'). These principles underpin robust C code; production projects always keep them in mind.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which header is used to sort an array?
- string.h (strcpy)
- math.h (sqrt)
- ctype.h (toupper)
- stdlib.h (qsort) Correct answer
Explanation: qsort is declared in stdlib.h.
2 Headers and functions
| Term | Meaning |
|---|---|
stdlib.h |
qsort |
string.h |
strlen |
math.h |
sqrt |
ctype.h |
toupper |