Summary - Arrays and pointers
- C course
- Beginner
- Lesson 82/116
- 5 min
Combine the array-pointer relationship to write an array sum function.
Summary: Arrays and pointers
In this group you saw the close link between arrays and pointers:
- An array name decays into the address of its first element.
p[i]and*(p + i)are the same.- Passing an array to a function turns it into a pointer; size is separate.
- The
end = arr + npattern builds a pointer loop. - Two-dimensional arrays are walked with nested loops.
Let's combine these in a short exercise.
Practice Summary exercise
Define int sum(int *arr, int n): sum the array with a for loop and return total. In main define int arr[3] = {10, 20, 30};. Start with int *p = arr;. Print *p, *(p + 2) and sum(arr, 3) on separate lines with printf. Output should be 10, 30, 60.
Starter code
#include <stdio.h>
/* write sum: take int pointer and size, sum with a for loop */
int main(void) {
int arr[3] = {10, 20, 30};
/* bind p to arr; print *p, *(p+2) and sum(arr, 3) */
return 0;
}Sample solution
#include <stdio.h>
int sum(int *arr, int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += arr[i];
}
return total;
}
int main(void) {
int arr[3] = {10, 20, 30};
int *p = arr;
printf("%d\n", *p);
printf("%d\n", *(p + 2));
printf("%d\n", sum(arr, 3));
return 0;
}Expected output
10 30 60
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is an array name, really?
- The array length
- A copy of the array
- Pointer to the first element Correct answer
- A NULL pointer
Explanation: An array name decays into the address of the first element.
2 Match concepts
| Term | Meaning |
|---|---|
arr |
array name = pointer |
*(p+i) |
pointer access |
int *arr |
function parameter |
p < end |
loop condition |
3 Access an element via pointer
int arr[3] = {10,20,30};
int *p = arr;
printf("%d", *(p + ____)); /* prints 30 */
int arr[3] = {10,20,30};
int *p = arr;
printf("%d", *(p + 2)); /* prints 30 */
Explanation: *(p + 2) gives the third element (30).