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.

Answer from jpalecek on Stack Overflow
Top answer
1 of 4
47

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.

2 of 4
13

No. A multidimensional array is a single block of memory. The size of the block is the product of the dimensions multiplied by the size of the type of the elements, and indexing in each pair of brackets offsets into the array by the product of the dimensions for the remaining dimensions. So..

int arr[5][3][2];

is an array that holds 30 ints. arr[0][0][0] gives the first, arr[1][0][0] gives the seventh (offsets by 3 * 2). arr[0][1][0] gives the third (offsets by 2).

The pointers the array decays to will depend on the level; arr decays to a pointer to a 3x2 int array, arr[0] decays to a pointer to a 2 element int array, and arr[0][0] decays to a pointer to int.

However, you can also have an array of pointers, and treat it as a multidimensional array -- but it requires some extra setup, because you have to set each pointer to its array. Additionally, you lose the information about the sizes of the arrays within the array (sizeof would give the size of the pointer). On the other hand, you gain the ability to have differently sized sub-arrays and to change where the pointers point, which is useful if they need to be resized or rearranged. An array of pointers like this can be indexed like a multidimensional array, even though it's allocated and arranged differently and sizeof won't always behave the same way with it. A statically allocated example of this setup would be:

int *arr[3];
int aa[2] = { 10, 11 }, 
    ab[2] = { 12, 13 }, 
    ac[2] = { 14, 15 };
arr[0] = aa;
arr[1] = ab;
arr[2] = ac;

After the above, arr[1][0] is 12. But instead of giving the int found at 1 * 2 * sizeof(int) bytes past the start address of the array arr, it gives the int found at 0 * sizeof(int) bytes past the address pointed to by arr[1]. Also, sizeof(arr[0]) is equivalent to sizeof(int *) instead of sizeof(int) * 2.

🌐
Reddit
reddit.com › r/c_programming › difference between pointer to pointer and 2d array
r/C_Programming on Reddit: Difference between pointer to pointer and 2d array
August 12, 2023 -

I know that I can go from one of the types 'char [1]' and 'char *' to the other. However, it seems not as easy with 'char [1][1]' and 'char **'.

In my main function I have

`char a[1][1];`

`a[0][0] = 'q';`

`printf("a: %p\n", a);`

`printf("*a: %p\n", *a);`

`printf("**a: %p\n", **a);`

I'm of course compiling with warnings and I know that gcc complains about the 5'th line as **a is actually of type char and not a pointer type. However running the code shows that 'a' and '*a' are actually the same pointer but '**a' is as expected something else (0x71 which I assume is related to 'q' in some way).

I'm trying to make sense of this and it seems that because *a and a are equal **a must also be equal to a because **a=*(*a)=*(a)=*a=a. It seems that the only error in this reasoning can be the types of a, *a, **a.

How is 'a' actually stored in memory? If 'a' is a pointer to another memory location (in my case 0x7fff9841f250) then surely *a should be the value at that memory address which in my case is also 0x7fff9841f250. So then **a would be the value at 0x7fff9841f250 which is the same value as 'a'... It seems that I cannot view the 2d array 'char a[1][1]' as pointers in a way that makes sense. But then how can I think of this type? What is the type and what does a, *a, **a, a[0], a[0][0] actually mean?

Can anyone help me make sense of this?

🌐
zakuarbor
zakuarbor.github.io › blog › double-pointers
A look at Double Pointers
October 25, 2020 - Some more “complex” data type requires the use of double pointers to implement the data structure. An extremely simple example is a multi-dimensional array. As the name implies, a multi-dimensional array is simply an array of arrays (i.e. having more than one dimension). A 2d array is composed of an array where each element is another array as seen in Example 3.
🌐
Brynmawr
cs.brynmawr.edu › Courses › cs246 › spring2014 › Slides › 16_2DArray_Pointers.pdf pdf
4/1/14 1 2D Arrays and Double Pointers Bryn Mawr College
Double Pointers · Bryn Mawr College · CS246 Programming Paradigm · 2D Arrays · • int A[m][n]; • The number of bytes: m*n*sizeof(int). • For 1D array, to access array elements: • A[i] • *(A+i) #define n 2 · #define m 3 · int A[n][m]; int A[2][3]={{1,2,3},{4,5,6}}; Access 2D Arrays Using Array Name ·
Top answer
1 of 2
2
Please see my comment to the question: it's not quite clear what to explain. · However, my guess is: you will be able to sort things out after this hint: due to the nature of C and C++ array, "2D" array is exactly the same way as "1D", as wall as all other array ranks. The ability to reference array elements with two or more indices is nothing but syntactic sugar. Please see: http://www.cplusplus.com/doc/tutorial/arrays[^]. · Among other things, pay attention for the section "Multidimensional arrays" and find the place saying "At the end, multidimensional arrays are just an abstraction for programmers…". · See also: http://en.wikipedia.org/wiki/Syntactic_sugar · However, when it comes to "double pointers", you can use slightly different thing, jagged arrays: http://en.wikipedia.org/wiki/Jagged_array],http://www.cplusplus.com/forum/general/69010http://stackoverflow.com/questions/3904224/declaring-a-pointer-to-multidimensional-array-and-allocating-the-array · (Anyway, I am not sure what did you mean by "double pointer", a pointer to pointer or double* :-).) · You may want to play with all this and ask more specific questions if you cannot get something. · —SA
2 of 2
0
By "how assign double pointer to 2D array" I assume you mean, "how to assign a pointer-to-double to a 2D array of double?" · In other words, how to assign a pointer to some element in the 2D array. · Here are example declarations for pointer and array. · C++ · double *pointer; · array[4][]; · · // Assign to element at row 1, column 2. · *pointer = &array[12// Note that these two do the same thing. · *pointer = 30]; · If by "double pointer" you mean "pointer to pointer", you will need to update your question to make it more clear.
🌐
Sololearn
sololearn.com › en › Discuss › 3022771 › how-to-initialise-double-pointer-to-2d-array
How to initialise double pointer to 2d array.. | Sololearn: Learn to code for FREE!
Now if you have a function tacking ... %d %d",Ptr[0][0],Ptr[0][1],Ptr[1][0]);} You simply can't the way you did. A double pointer doesn't ......
🌐
Quora
quora.com › How-do-I-make-2d-array-using-double-pointer
How to make 2d array using double pointer - Quora
Answer (1 of 6): Pointer is a variable which holds the address of another variable and array is collection of consecutive location of a particular data type. So we can use pointer to allocate memory for an array. allocating memory for integer type can be done like this : [code]int *num; int n =...
🌐
YouTube
youtube.com › watch
Pointers and 2-D arrays - YouTube
See complete series on pointers here:http://www.youtube.com/playlist?list=PL2_aWCzGMAwLZp6LMUKI3cc7pgGsasm2_In this lesson, we will see how we can work with...
Published   September 7, 2013
Find elsewhere
🌐
iBiblio
ibiblio.org › pub › languages › fortran › append-c.html
Arrays and pointers in C
The dimensions doesn't appear in any declaration, so you can add them to the formal argument list. The manual array indexing will probably slow down execution. */ int func3(short *mat) { register short i, j; printf(" Declare as single-pointer, manual offset computation: "); for(i = 0 ; i < 3 ; i++) { printf("\n"); for(j = 0 ; j < 3 ; j++) { printf("%5.2d", *(mat + 3*i + j)); } } printf("\n"); return; } /* Method #4 (double pointer, using an auxiliary array of pointers) ================================================================ With this method you can create general-purpose routines, if you allocate "index" at run-time.
Top answer
1 of 5
28
                                 (*ptr)      (*ptr+1)     (*ptr+2)
                                   |            |            |
             __________      ______v____________v____________v____________
  ptr------>|   *ptr   |--->|  *(*ptr)   |  *(*ptr+1)  |*(*ptr+2) |       |
            |__________|    |____________|_____________|__________|_______|
 (ptr+1)--->| *(ptr+1) |     ____________ _____________ __________________
            |__________|--->|*(*(ptr+1)) |*(*(ptr+1)+1)|          |       |
            |          |    |____________|_____________|__________|_______|
            |__________|          ^             ^
                                  |             |
                              *(ptr+1)     *(ptr+1)+1

2D array with double pointers that means that you have a main array and the elements of the main array are pointers (or addresses) to a sub arrays. As indicated in above figure

so if you have defined a double pointer as a pointer of this 2D array let's say int **ptr

so ptr is ponting to the main array which will contains pointers to sub arrays. ptr is ponting to the main array that's means ptr is pointing to the first element of the main array so ptr + 1 is pointing to the second element of the main array.

*ptr this means the content of the first element which the ptr is pointing on. And it is a pointer to a subarray. so *ptr is a pointer to the first subarray (the subarray is an array of int). so *ptr is pointing to the first element in the first subarray. so *ptr + 1 is a pointer to the second element in the first subarray

2 of 5
9

*(ptr+i) is equals to ptr[i] and *(ptr+1) is ptr[1].

You can think, a 2-D array as array of array.

  • ptr points to complete 2-D array, so ptr+1 points to next 2-D array.

In figure below ptr is 2-D and number of columns are 3

Original figure made by Mr. Kerrek SB, here , you should also check!

+===============================+==============================+====
|+---------+----------+--------+|+----------+---------+--------+|
||ptr[0,0] | ptr[0,1] | ptr[0,2]|||ptr[1,0] |ptr[1,1] | ptr[1,2]|| ...
|+---------+----------+--------+++----------+---------+--------++ ...
|            ptr[0]             |           ptr[1]              |
+===============================+===============================+====
   ptr

*(*ptr+1) = *( ptr[0] + 1 ) = ptr[0][1]

Understand following:

ptr points to complete 2-D.

*ptr = *(ptr + 0) = ptr[0] that is first row.

*ptr + 1 = ptr[1] means second row

*(*ptr+1) = *(*(ptr + 0) + 1 ) = *(ptr[0] + 1) = ptr[0][1]

Array 0 Elements:
1  2  3  4 

And GDB Output:

(gdb) p *(*ptr+1)
$1 = 2  

that is correct 2 this can be read using ptr[0][1].

🌐
Carnegie Mellon University
cs.cmu.edu › ~ab › 15-123S09 › lectures › Lecture 06 - Pointer to a pointer.pdf pdf
Lecture 06 2D Arrays & pointer to a ...
2-D arrays are represented as a · contiguous block of n blocks each with size m (i.e. can · hold m integers(or any data type) in each block). The ... A[1], A[2] etc.. We can access array elements using [ ] operator as A[i] or · using pointer operator *(A+i).
🌐
GeeksforGeeks
geeksforgeeks.org › c language › dynamically-allocate-2d-array-c
How to dynamically allocate a 2D array in C? - GeeksforGeeks
January 10, 2025 - #include <stdio.h> #include <stdlib.h> int main() { int r = 3, c = 4, len = 0; int *ptr, **arr; int count = 0, i, j; len = sizeof(int*) * r + sizeof(int) * c * r; arr = (int**)malloc(len); // ptr is now pointing to the first element of the 2D // array // it points to the memory just after the row pointers // allocated memory ptr = (int*)(arr + r); // for loop to point rows pointer to appropriate // location in 2D array for (i = 0; i < r; i++) arr[i] = (ptr + c * i); for (i = 0; i < r; i++) for (j = 0; j < c; j++) arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", arr[i][j]); return 0; }
🌐
Spiceworks Community
community.spiceworks.com › programming & development
2D Array and Double Pointer in C - Programming & Development - ...
August 5, 2011 - To get answer on your question let consider what actions take place when expression **arr is used. In expressions the name of an array is converted to a pointer to its first element. As arr is a two-dimensional array when arr is converted to int ( * )[4]. When you apply derederencing *arr you ...
Top answer
1 of 2
5

How do you create a single pointer array? You do this:

int* myArray = new int[n];

What does this mean? It has two parts. First part is reserving a pointer int* we call it myArray, and the second part is that you reserve n elements, each with size int in memory (this is an array, right?), and you take the address of that array and you save it in the variable myArray.

Now you want a 2D array, which is an array of an array. So Every element of this new array of array is one of these, that we talked about up there. How do we reserve this? We do:

new int*[n];

Because we are reserving n slots, each with type int*, that we talked about before.

Now what is the type of the return value? It's an array of an array, or a "pointer to an array, and the latter is also a pointer to an array", so you write it as

(int*)*

Or

int**

so it becomes

int** array = new int*[n];
2 of 2
3

int** array is a pointer to a pointer to an int. So by doing this:

int** array = new int*[n];

you are creating a section of memory that holds n int* pointers and pointing array at that memory. For each of these pointers that you have created, it is possible to create a set of ints like so:

for (auto i = 0; i < n; ++i)
    array[i] = new int[n];

The resulting memory will look like this:

array -> [       int*     |     int *     |   .... n
         [int | int | ...][int | int | ...][  ... n

This is however, much much easier if you use some of the std things in c++, ie a std::vector :

std::vector<std::vector<int>> arr(std::vector<int>(0, n), n);

and you are done ...

🌐
Quora
quora.com › Is-it-possible-to-have-a-double-pointer-point-to-a-two-dimensional-matrix-in-C-language
Is it possible to have a double pointer point to a two dimensional matrix in C language? - Quora
Answer (1 of 2): Assuming you have something like this: [code]int a1[5]; int a2[5]; int a3[5]; size_t* dim2 = malloc(3 * sizeof(int*)); *(dim2) = a1; *(dim2 + 1) = a2; *(dim2 + 2) = a3; [/code]It's not the most beautiful code, but sometimes declaring everything one by one can be less confusing,...
🌐
Medium
medium.com › @muirujackson › use-of-double-pointers-in-c-d94e086a13fc
Use of Double Pointers in C?. In C, we use pointers to hold memory… | by Muiru Jackson | Medium
April 28, 2023 - In the code above, we first declare a double pointer variable “matrix” that will hold the address of the two-dimensional array. We then allocate memory for the rows of the array using the malloc function. Since each row of the array is itself a one-dimensional array, we use a single pointer to hold the address of each row.
🌐
Medium
medium.com › @ryan_forrester_ › double-pointers-in-c-a-practical-guide-ffb91c2628b7
Double Pointers in C++: A Practical Guide | by ryan | Medium
January 7, 2025 - If you try SolvePro and it doesn’t help, email me directly at [email protected], I want to know why so we can make it better. Let’s look at a practical application of double pointers in image processing. We’ll create a simple grayscale image represented as a 2D array and apply a basic ...
🌐
Codedamn
codedamn.com › news › c programming
What are double pointers in C?
March 10, 2024 - This is because a 2D array can be thought of as an array of pointers, where each pointer corresponds to a row in the array. To dynamically create a 2D array, you first declare a double pointer. Then, you allocate memory for each row using a ...
🌐
Cplusplus
cplusplus.com › forum › beginner › 43003
Converting two dimensional array to doub - C++ Forum
So perhaps I can reduce the two dimensional array into a one-dimensional one, as your article highlights: and pass this to a function, which does not require its dimensions, along with its width: ... That's one way to do it. Code would look more like this: But of course then you have to remember to delete[] t. Your funkshin function is more like it's allocating an entirely separate 2D array and copying all the data over, which is a little much.