int main(){
int a[10][10];
int **ptr =(int **)a;
cout<<a<<endl<<ptr<<endl;
cout<<*a<<endl<<*ptr<<endl;
return 0;
}
Output of this code on my computer is
0021FC20
0021FC20
0021FC20
CCCCCCCC
Why is "a" equal to "*a"? why isn't *a equal to *ptr?
Why is
a
equal to*a
?
When used in a context that requires a pointer, an array will be converted to a pointer to its first element. a
is an array of arrays; so it will decay to a pointer to the first array. *a
is the first array, and will decay to a pointer to the first integer in that array. Both of these exist at the same location, so the two pointers will have equal values.
why isn't *a equal to *ptr?
Because the conversion from an array of arrays, to a pointer-to-pointer, is not valid. You have forced the conversion using a cast - the dangerous C-style cast, which in this case acts like reinterpret_cast
- so *ptr
will read the first few bytes of the array and interpret that as a pointer (probably - the behaviour here is undefined, so in principle anything could happen). There is no pointer in the memory pointed to by ptr
, so *ptr
will certainly not give you a valid pointer.
Why is a equal to *a?
Since you cannot print an array, a
is implicitly converted from int[10][10]
to int(*)[10]
. So what actually gets printed instead of a
is a pointer to the first line of a
.
*a
is the first line of the array, and that in turn gets converted to a pointer to the first element.
Since an array has the same address as its first element, you get the same value twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With