+ 2
Could you please explain more about accessing arrays by pointers?
the array is a pointer to the first element what if I want to access the second element using pointer
1 Answer
+ 5
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int *p = arr;
cout << arr << endl; // address of arr (first element)
cout << *arr << endl; // value of first element in the arr
cout << p << endl; // address of arr (first element)
cout << *p << endl; // value of first element in the arr
p++; // increment the pointer to the next memory address
cout << p << endl; // address of arr (second element)
cout << *p << endl << endl; // value of second element in the arr
p = arr; // reset the address held by the pointer p to the begining of the array
// loop over the array using a pointer
// 9 is one memory address past the end of the array
// this is used when using < less than operator
// as using the last elements address would only
// get up to the element before it
for(int *i = arr; i < &arr[9]; i++) {
cout << *i << " ";
}
cout << endl;
// alternate way of gettting the length/size of an array
for(int *i = arr; i < &arr[sizeof(arr)/sizeof(arr[0])]; i++) {
cout << *i << " ";
}
return 0;
}
You can use pre and post fix operators to move the pointer forward and backward over the array.
You can also just use basic math to add/subtract to the pointer. (be careful)
Hope this helps.