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
- Start with n holds 2
- Do this Read through its address
- Result 2
#include <stdio.h>
int main(void) {
int n = 2;
int *address = &n;
printf("%d\n", *address);
}
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.
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
#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;
}
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.