Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 2d array a double pointer? [duplicate]

int main() {     matrix[2][4] = {{11,22,33,99},{44,55,66,110}};     int **ptr = (int**)matrix;     printf("%d%d",**matrix,*ptr); } 

But when a 2-d array is passed as a parameter it is typecasted into (*matrix)[2] .. what type does the compiler store this array as... is it storing as a 2-d array or a double pointer or an pointer to an array .. If it is storing as an array how does it interprets differently at different situations like above. Please help me understand.

like image 860
Angus Avatar asked Sep 28 '11 16:09

Angus


People also ask

How can use 2D array in double pointer?

acData [i][j] = *(*(acData + i) + j) ———————->2D array in form of pointer. Note Array elements stored in a consecutive memory block, so we can access the elements of the array using the pointer.

Are 2D arrays pointers?

A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element.

Is a double pointer a matrix?

Explanation: In the above code, as “matrix” is a double pointer it uses malloc function which dynamically allocates memory for the matrix of 5 rows and 5 columns.

What do you call a 2 dimensional array?

The 2D array is organized as matrices which can be represented as the collection of rows and columns.


1 Answers

Is 2d array a double pointer?

No. This line of your program is incorrect:

int **ptr = (int**)matrix; 

This answer deals with the same topic

If you want concrete image how multidimensional arrays are implemented:

The rules for multidimensional arrays are not different from those for ordinary arrays, just substitute the "inner" array type as element type. The array items are stored in memory directly after each other:

matrix: 11 22 33 99 44 55 66 110         -----------               the first element of matrix                     ------------  the second element of matrix 

Therefore, to address element matrix[x][y], you take the base address of matrix + x*4 + y (4 is the inner array size).

When arrays are passed to functions, they decay to pointers to their first element. As you noticed, this would be int (*)[4]. The 4 in the type would then tell the compiler the size of the inner type, which is why it works. When doing pointer arithmetic on a similar pointer, the compiler adds multiples of the element size, so for matrix_ptr[x][y], you get matrix_ptr + x*4 + y, which is exactly the same as above.

The cast ptr=(int**)matrix is therefore incorrect. For once, *ptr would mean a pointer value stored at address of matrix, but there isn't any. Secondly, There isn't a pointer to matrix[1] anywhere in the memory of the program.

Note: the calculations in this post assume sizeof(int)==1, to avoid unnecessary complexity.

like image 155
jpalecek Avatar answered Sep 19 '22 14:09

jpalecek