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.