I made a pointer called *p
and init with arr
and output the result of arr
and &arr
;
#include<bits/stdc++.h>
using namespace std;
int main(){
int arr[9]={1,2,3,4,5,6,7,8,9};
cout<<arr<<endl;
cout<<&arr<<endl;
int *p=arr;
cout<<p<<endl;
}
I ran it, everything is working fine and have output likes this
0xfe0dff5d0
0xfe0dff5d0
0xfe0dff5d0
l found that cout<<arr<<endl
and cout<<&arr<<endl
both show the same answer as 0xfe0dff5d0
In some turotorials of C++, i noted that to use pointer to control a array should be like int *p=arr // arr refers to an array
. But i found that arr
and &arr
gives the same output, so i began to try to use &arr
to init a pointer to access to an array. And i failed with error like this:
ptr-array.cpp:9:13: error: cannot convert 'int (*)[9]' to 'int*' in initialization
9 | int *p2=&arr;
| ^~~~
| |
| int (*)[9]
I'm puzzled with why arr
and &arr
gives the same output, but i can't init a pointer with &arr
.
In addition:
As the comment under this question, i aslo found that &arr[0]
aslo can init a pointer to access a array.
In short: i'm puzzled with why i can't init a pointer with &arr
but init a pointer with arr
and &arr[0]
though all of them direct to the same address in RAM