I know that the following is not correct:
int arr[2][3] = {}; //some array initialization here int** ptr; ptr = arr;
But I am quite surprised that the following lines actually work
int arr[2][3] = {}; //some array initialization here auto ptr = arr; int another_arr[2][3] = {}; //some array initialization here ptr = another_arr;
Can anyone possibly explain what is the type assigned to ptr in the second block of code, and what happened underneath?
An array is treated as a pointer that points to the first element of the array. 2D array is NOT equivalent to a double pointer! 2D array is "equivalent" to a "pointer to row". The information on the array "width" (n) is lost.
A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creating a 2D integer pointer array of 5 rows and 5 columns. The element of the 2D array is been initialized by assigning the address of some other element.
In computer programming, an array of pointers is an indexed set of variables, where the variables are pointers (referencing a location in memory). Pointers are an important tool in computer science for creating, using, and destroying all types of data structures.
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure.
Well, arrays decay to pointers when used practically everywhere. So naturally there's decay going on in your code snippet too.
But it's only the "outer-most" array dimension that decays to a pointer. Since arrays are row-major, you end up with int (*)[3]
as the pointer type, which is a pointer to a one-dimensional array, not a two dimensional array. It points to the first "row".
If you want ptr
's deduction to be a pointer to the array instead, then use the address-of operator:
auto ptr = &arr;
Now ptr
is int(*)[2][3]
.
In
auto ptr = arr;
arr
decays into a pointer to its first element in the normal way; it's equivalent to
auto ptr = &arr[0];
Since arr[0]
is an array of three int
s, that makes ptr
a int (*)[3]
- a pointer to int[3]
.
another_arr
decays in exactly the same way, so in
ptr = another_arr;
both sides of the assignment have the type int (*)[3]
, and you can assign a T*
to a T*
for any type T
.
A pointer to arr
itself has type int(*)[2][3]
.
If you want a pointer to the array rather than a pointer to the array's first element, you need to use &
:
auto ptr = &arr;
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