Pointer to pointer and bidimensional arrays.

Hello :)
I've got three questions,could you help me please?

1.Why isn't this working ?

1
2
int arr[2][3];
int** ptp=arr;


If an array is a pointer, shouldn't be a double-array a double-pointer(pointer to pointer) ?



2. Which is the difference in the following statements ?
1
2
int *p[3];
int **ptp;

Can I use both p and ptp the same ?



3.Which is the difference between:

 
int *p[3]; 
and
 
int (*p)[3];


I'm trying to finally understand the pointers...
Thanks in advance :)
anyone ? :(
1. Because a 2D array is not an array of pointers, it is a single-dimension array with syntactic sugar to make it look 2D by using 2D-to-1D index conversion.

2. The first is an array of pointers, the second is a pointer to a pointer. There are some cases where you may not be able to use them interchangeably.

3. The first is an array of pointers, the second is a pointer to an array.
1) It is not working because they are not type-compatible. You are trying to assign different things.

No.

2) The first is a array of three pointers-to-int. The second is a pointer to a pointer-to-int.

It depends on what you mean by "use" and "the same".

3) It depends on context. It does solve your problem though. Did someone suggest it to you?

To do what you want you need to have the proper type. The difficulty comes in part because of the way that C and C++ syntax spreads out the declaration of array types to both sides of the identifier.

Instead of saying int[2][3] arr and int[3]* ptp, all the stuff in square brackets goes on the other side of the identifier:

1
2
int arr[2][3];      // arr is an array of 2 by 3 integers.
int (*ptp)[3]=arr;  // (ptp is a pointer) to an array of three integers 

Another confusion is that in C and C++, a multidimensional array is really just a fancy one-dimensional array that you can index in a friendly way, and it has type information encoded with it (meaning, it knows its shape) -- so long as you don't do anything to make it degenerate into a pointer.

So the ptp pointer we created works like any other pointer, say pointer to integer:

1
2
3
4
5
int xs[10];
int* xp = xs;  // xp points to one or more integers

cout << xp[7] << endl;  // works fine because we use the [7] to access 
                        // the eighth integer from the one xp points to. 

So when we create the pointer to the array, we need to create a pointer to the array's elements, which are themselves arrays, just like the integers. Hence:

1
2
3
4
5
6
int arr[2][3] = {{1,2,3},{4,5,6}};
int (*ptp)[3] = arr;

cout << ptp[1][0] << endl;  // index 1st element (which is {4,5,6}), 
                            // then 0th element of that (which is 4).
                            // Hence, it prints '4'. 

Hope this helps.
Topic archived. No new replies allowed.