Reputation: 133
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.
arr
is the same as the address of the first elements of the array. *arr
gives me what is the int at that location as does arr[0]
.p
is a pointer and gets assigned arr
which is the address of the first element. So in essence *p
is the same as *arr
and p[0]
is the same as arr[0]
.arrPtr
is a pointer to an array of ten integers. Why doesn't *arrPtr
or arrPtr[0]
yield me the value 9?arrRef
is a reference to an array of ten integers and unlike in the point above *arrRef
or arrRef[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
Upvotes: 3
Views: 147
Reputation: 311146
*arrPtr
or arrPtr[0]
yields an object of the type int[10]
Used in the operator <<
the array is explicitly converted to pointer of type int *
and the overloaded operator <<
for the parameter of const void *
is selected for such an expression.
You can see that these outputs
arr: 0xbf843e28
and
*arrPtr: 0xbf843e28
arrPtr[0]: 0xbf843e28
coincide.
If you want to output the first element of the array you should write either
std::cout << **arrPtr << std::endl;
std::cout << ( *arrPtr )[0] << std::endl;
std::cout << arrPtr[0][0] << std::endl;
std::cout << *arrPtr[0] << std::endl;
To make it more clear you can introduce a reference such a way
int ( &arrRef )[10] = *arrPtr;
and then write
std::cout << *arrRef << std::endl;
std::cout << arrRef[0] << std::endl;
Upvotes: 7