Lesson 16 · 16 of 20
Pointers and arrays · C
See how pointers and arrays are related in C: the array name as an address, pointer arithmetic and arrays passed as function parameters.

An array's name works as the address of its first element: int *p = marks; makes p point at marks[0], no & needed. That is why *p is 6.
With pointer arithmetic, p + 1 points to the next element, not the next byte: C moves forward by the size of an int. *(p + 1) is 8, and p[2] is just another way of writing *(p + 2). The for with q walks the array by moving a pointer from marks up to marks + n, just past the end.
When you pass an array to a function, what travels is that address. So the function does not know how many elements there are, and you have to pass count too. And that is why add_bonus does change the original array, unlike a plain int: every mark goes up by one.
In average, the parameter is const double *values: `const` promises that the function will only read the array, and the compiler would complain if it tried to change it. It is a good habit for functions that only look.
Code · main.c
#include <stdio.h>// An array parameter is really a pointer, so pass the length too.double average(const double *values, int count) { double sum = 0; for (int i = 0; i < count; i++) sum += values[i]; return sum / count;}// Through the pointer, the function changes the original array.void add_bonus(int *marks, int count, int bonus) { for (int i = 0; i < count; i++) marks[i] += bonus;}int main(void) { int marks[] = {6, 8, 5, 9, 7}; int n = sizeof(marks) / sizeof(marks[0]); int *p = marks; // the array name is the address of marks[0] printf("*p = %d, *(p + 1) = %d, p[2] = %d\n", *p, *(p + 1), p[2]); // p + 1 moves one element forward, not one byte. for (int *q = marks; q < marks + n; q++) printf("%d ", *q); printf("<- marks\n"); add_bonus(marks, n, 1); for (int i = 0; i < n; i++) printf("%d ", marks[i]); printf("<- after the bonus\n"); double temps[] = {12.5, 15.0, 9.5}; printf("Average temperature: %.2f\n", average(temps, 3)); return 0;}Output · cc main.c -o main && ./main
*p = 6, *(p + 1) = 8, p[2] = 5 6 8 5 9 7 <- marks 7 9 6 10 8 <- after the bonus Average temperature: 12.33
Key points
- An array's name is the address of its first element.
p + imovesielements forward;p[i]is*(p + i).- A function that takes an array gets a pointer: pass the size as well.
- The function can change the original array.
conston the parameter says it will only be read.
Exercise
Write int find_max(const int *values, int count) that returns the position of the highest mark, and use it to print that mark after the bonus.