C
Summary - Standard library
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.
Exercise 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));.
Show example 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;
}
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.
Test yourself
-
Which header is used to sort an array?
- string.h (strcpy)
- math.h (sqrt)
- ctype.h (toupper)
- stdlib.h (qsort)
Show answer
stdlib.h (qsort) — qsort is declared in stdlib.h.
-
Headers and functions
- stdlib.h
- qsort
- string.h
- strlen
- math.h
- sqrt
- ctype.h
- toupper
Next lesson: argc and argv