Array elements occupy contiguous storage. Except in cases such as sizeof and taking the whole array's address, an array name converts to the first element's address, so int *p = arr and int *p = &arr[0] use the same starting point. Pointer arithmetic advances in units of the pointed-to type.
#include <iostream>
using namespace std;
int main() {
int arr[] = {4, 1, 6, 7};
int *p = arr;
cout << *p << endl;
cout << *(p + 2) << endl;
return 0;
}KNOWLEDGE QUIZ
Move p across an array
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
Array parameters and sizeof
The parameters int arr[] and int *arr describe the same pointer parameter. A function receives the first element's address without a length. While the real array still exists in main, sizeof(arr)/sizeof(arr[0]) computes the element count; inside search, sizeof(arr) is only the pointer size.
#include <iostream>
using namespace std;
int search(const int *arr, int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {4, 7, 1, 3, 9, 2};
int n = sizeof(arr) / sizeof(arr[0]);
cout << search(arr, n, 3) << endl; // 3
return 0;
}KNOWLEDGE QUIZ
Sum an array with pointer traversal
Implement sum_array(const int *arr, int n). Move a pointer from arr to arr + n and add *p each time. Test with {4, 1, 6, 7}.
- Accept the first-element pointer and element count.
- Set end = begin + count.
- Accumulate *p while advancing p, then return total.
Reverse an array with two pointers
Implement reverse(int *arr, int n). Point left at the first element and right at the last, move inward, and swap in place. Test {2, 4, 6, 8, 10}.
- Point left at the first element and right at the last.
- While left < right, swap *left and *right.
- Advance left and retreat right each round, then print the array.