+ 4
Array pointer
I have pointer like that Int arr[] ={1,2,3}; Int *p; p = arr; Cout <<p<<endl; My question is. Why when im trying to show first element of array I get address of this array of course I can do it like that Cout <<p[0]; but here I get value 1 but in cout <<p; I get the address of the first element What is the difference between it ? And why I'm getting adress not value ? After all, the name of the array should point to the first element p is pointing to first element but what's difference between p and p[0]
4 Respuestas
+ 6
If you cout p, you are showing the address that's stored in that pointer.
If you cout *p, you are accessing the value stored at that address.
The difference between arr and arr[0] is the same.
You could also write *arr (getting the first element) or *(arr+i) (getting the element at that index.
+ 3
What I think is Virozz ,p is a variable that is containing address of the array now ,and when you do p[0] it actually refers to the 0th index of array since it is pointing to the array similarly like arr is pointing to the array and gives you same value for arr[0]
+ 2
But how it's doing that p is storing adress but p[0] is already storing first element
+ 2
Virozz "p" is pointing to the first element of the array "arr".
You should note that you have created only one pointer (that is 'p' ) which is traversing the array to access it's elements.
so just like Abhay and HonFu already explained :-
p[n] is same as *(p + n)
So p[0] can be considered as *(p + 0) which is initial address of 'p'.