Pointer to array
- C course
- Beginner
- Lesson 78/116
- 5 min
Learn to access array elements with pointer arithmetic.
Pointer arithmetic with arrays
Adding an integer to a pointer jumps to the next element. p + 1 moves forward by the size of the pointer's type; 4 bytes for int.
int arr[3] = {10, 20, 30};
int *p = arr;
printf("%d", *(p + 2)); /* 30 */
printf("%d", p[2]); /* 30: same thing */p[i] and *(p + i) mean exactly the same thing. Index notation is more readable, pointer notation more flexible.
p[i] and *(p+i) are the same
In C the p[i] notation is actually shorthand for *(p + i). They are fully equivalent; the compiler produces the same machine code.
int arr[4] = {5, 10, 15, 20};
int *p = arr;
printf("%d", p[0]); /* 5 */
printf("%d", *(p + 1)); /* 10 */
printf("%d", p[2]); /* 15 */Which form you choose is a matter of style. Index notation is easier for beginners.
Practice Mix both notations
Define int arr[4] = {5, 10, 15, 20};. Start with int *p = arr;. With four printf calls print p[0], *(p + 1), p[2] and *(p + 3) on separate lines. Output should be 5, 10, 15, 20.
Starter code
#include <stdio.h>
int main(void) {
int arr[4] = {5, 10, 15, 20};
/* bind p to arr; print p[0], *(p+1), p[2], *(p+3) */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int arr[4] = {5, 10, 15, 20};
int *p = arr;
printf("%d\n", p[0]);
printf("%d\n", *(p + 1));
printf("%d\n", p[2]);
printf("%d\n", *(p + 3));
return 0;
}Expected output
5 10 15 20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Access the third element
int arr[5] = {1,2,3,4,5};
int *p = arr;
printf("%d", *(p + ____)); /* prints 3 */
int arr[5] = {1,2,3,4,5};
int *p = arr;
printf("%d", *(p + 2)); /* prints 3 */
Explanation: *(p + 2) gives the third element (3).
2 Match access forms
| Term | Meaning |
|---|---|
p[0] |
first element |
p[1] |
second element |
*(p+2) |
third element |
p+3 |
fourth address |
3 p = arr; p[2] is equal to which?
- *(p + 1)
- *(p + 3)
- *(p + 2) Correct answer
- *p
Explanation: p[2] and *(p + 2) are the same.