Arrays, pointers and sorting

Arrays and their length, pointers, sorting with qsort, and struct.

Runs in Zerethon IDE · C (GCC 14) Official C documentation ↗
main.c
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    const char *name;
    int age;
} Person;

static int by_value(const void *a, const void *b) {
    int x = *(const int *) a, y = *(const int *) b;
    return (x > y) - (x < y);
}

static int by_age(const void *a, const void *b) {
    return ((const Person *) a)->age - ((const Person *) b)->age;
}

int main(void) {
    int scores[] = {70, 95, 8, 82};
    size_t n = sizeof scores / sizeof scores[0];
    qsort(scores, n, sizeof scores[0], by_value);
    for (size_t i = 0; i < n; i++) printf("%d ", scores[i]);
    printf("(%zu items)\n", n);

    int *p = &scores[1];
    printf("%d %d\n", *p, *(p + 1));

    Person people[] = {{"bob", 31}, {"amy", 25}};
    qsort(people, 2, sizeof(Person), by_age);
    printf("%s %d\n", people[0].name, people[0].age);
    return 0;
}

Output

8 70 82 95 (4 items)
70 82
amy 25
  • sizeof array / sizeof array[0] gives the length only where the array is declared, not inside a function that received it.
  • C does not check indexes: reading scores[10] is undefined behaviour, not an error message.
  • p->age is (*p).age for a pointer to a struct.

Related topics

Official references