typestar

Arrays decay to pointers in C

An array argument is really a pointer, which is why the callee needs a length.

#include <stdio.h>

static void inside(int values[]) {
    printf("in the callee: %zu\n", sizeof(values));
}

int sum(const int *values, size_t n) {
    int total = 0;
    for (size_t i = 0; i < n; i++) {
        total += values[i];
    }
    return total;
}

void decay(void) {
    int numbers[6] = {1, 2, 3, 4, 5, 6};
    size_t count = sizeof(numbers) / sizeof(numbers[0]);

    printf("at the definition: %zu, count %zu\n", sizeof(numbers), count);
    inside(numbers);
    printf("sum %d\n", sum(numbers, count));
}

How it works

  1. Inside the function sizeof measures the pointer, not the array.
  2. The caller must pass the element count separately.
  3. At the definition site, though, sizeof still sees the array.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
472
Tokens
151
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 101 seconds.

Type this snippet

Step 4 of 5 in Pointers, step 4 of 25 in Pointers & memory.

← Previous Next →