Coding Techniques
C Library Functions · Study material
Sort structures with qsort and a two-key comparator
The comparator decides the order: compare the main key first and fall back to a second key for ties. Returning a comparison result instead of a subtraction avoids overflow.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct player { const char *name; int score; };
/* Highest score first; equal scores in name order */
static int ranking(const void *a, const void *b) {
const struct player *p = a, *q = b;
if (p->score != q->score)
return q->score > p->score ? 1 : -1;
return strcmp(p->name, q->name);
}
int main(void) {
struct player t[] = {{"Ravi", 70}, {"Asha", 92}, {"Meera", 70}, {"Kabir", 85}};
qsort(t, 4, sizeof t[0], ranking);
for (int i = 0; i < 4; i++)
printf("%d. %-6s %d\n", i + 1, t[i].name, t[i].score);
return 0;
}
1. Asha 92 2. Kabir 85 3. Meera 70 4. Ravi 70
Copying strings safely
char dst[16];
/* strncpy does NOT terminate when the source is too long */
strncpy(dst, src, sizeof dst - 1);
dst[sizeof dst - 1] = '\0';
/* simpler: snprintf always terminates and reports truncation */
if (snprintf(dst, sizeof dst, "%s", src) >= (int) sizeof dst) {
/* src was cut */
} memcpy vs memmove
char s[] = "abcdef";
memmove(s + 2, s, 4); /* overlapping: OK, s becomes "ababcd" */
memcpy(s + 2, s, 4); /* overlapping: undefined behaviour */memcpy may copy in any order for speed; memmove behaves as if it copied through a temporary buffer.
Good library habits
- Look up the return value of every function you use – and check it.
- Pass buffer sizes with
sizeof, not magic numbers. - Prefer
strtol/strtodtoatoi/atof, andsnprintftosprintf. - Write comparators as
(a > b) - (a < b). - Seed
rand()once withsrand(), not before every call.