Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2Dimensional Array Pointer manipulation in C++

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?

like image 660
Ganesh Avatar asked Jan 17 '23 07:01

Ganesh


2 Answers

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.

like image 107
Mike Seymour Avatar answered Jan 24 '23 21:01

Mike Seymour


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.

like image 43
fredoverflow Avatar answered Jan 24 '23 23:01

fredoverflow