Lesson contents

C — Pointers and array lengths

Pass an array and its length to a function that changes elements in place.

A simple example

Follow a pointer

  1. Start with n holds 2
  2. Do this Read through its address
  3. Result 2
The pointer holds the address of n. Dereferencing it reads the value at that address.
lesson.c
#include <stdio.h>

int main(void) {
    int n = 2;
    int *address = &n;
    printf("%d\n", *address);
}
Output
2
Advertisements

Change an array through a pointer

An array expression passed to this function becomes a pointer to its first element. Pass the length separately. Writing through values[i] changes the original array. An incorrect count can access memory outside it.

Before the update: 4 and 7. Scale each count: Multiply by 2. Same shelves: 8 and 14.
Update two shelf counts in place

Two shelf labels hold counts of 4 and 7. Pass the array and its length to a helper that doubles each count. A later shelf check reads 8 and 14 from the original array.

Run the example

C17. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 lesson.c -o lesson
./lesson
lesson.c
#include <stdio.h>

void double_values(int *values, size_t count) {
    for (size_t i = 0; i < count; ++i) values[i] *= 2;
}

int main(void) {
    int readings[] = {4, 7};
    double_values(readings, sizeof readings / sizeof readings[0]);
    printf("%d %d\n", readings[0], readings[1]);
    return 0;
}
Output
8 14

Doubling the two stored integers produces 8 and 14 in the caller.

Try it yourself

What if count is 1?

Check your answer

Only the first element doubles. The pair becomes 8 and 7.

GNU C Language Manual

Related tags

  • C
  • pointers
  • arrays
  • memory