I wrote the following code to try to understand how we can use pointers to arrays and references to arrays. Here is my thought process of what is happening.
arris the same as the address of the first elements of the array.*arrgives me what is the int at that location as doesarr[0].pis a pointer and gets assignedarrwhich is the address of the first element. So in essence*pis the same as*arrandp[0]is the same asarr[0].- Here i don't understand what is happening.
arrPtris a pointer to an array of ten integers. Why doesn't*arrPtrorarrPtr[0]yield me the value 9? arrRefis a reference to an array of ten integers and unlike in the point above*arrReforarrRef[0]does yield value 9.
Here is my code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
int arr[10] = {9, 18, 31, 40, 42};
cout << "arr: " << arr << endl;
cout << "*arr: " << *arr << endl;
cout << "arr[0]: " << arr[0] << endl;
cout << endl;
int *p = arr;
cout << "p: " << p << endl;
cout << "*p: " << *p << endl;
cout << "p[0]: " << p[0] << endl;
cout << endl;
int (*arrPtr)[10] = &arr;
cout << "arrPtr: " << arrPtr << endl;
cout << "*arrPtr: " << *arrPtr << endl;
cout << "arrPtr[0]: " << arrPtr[0] << endl;
cout << endl;
int (&arrRef)[10] = arr;
cout << "arrRef: " << arrRef << endl;
cout << "*arrRef: " << *arrRef << endl;
cout << "arrRef[0]: " << arrRef[0] << endl;
}
Here is my output:
arr: 0xbf843e28
*arr: 9
arr[0]: 9
p: 0xbf843e28
*p: 9
p[0]: 9
arrPtr: 0xbf843e28
*arrPtr: 0xbf843e28
arrPtr[0]: 0xbf843e28
arrRef: 0xbf843e28
*arrRef: 9
arrRef[0]: 9