how to use a pointer to point a 2d array?
i have tried some code what is wrong in it ? can anybody explain these things in detail i always stuck in multi dimensional array and pointer things!
thanks in advance! please help me out in these things!
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int main()
{
int **arry;
int a[2][2]={{0,1},{2,3}};
arry=a;
cout<<arry[0][0];
return 0;
}
//Create your 2D array
int **array = newint[ 2 ];
for( int i = 0; i < 2; ++i )
{
array[ i ] = newint[ 2 ];
}
//Then set them to NULL
for( int i = 0; i < 2; ++i )
{
for( int j = 0; j < 2; ++j )
{
array[ i ][ j ] = NULL;
}
}
//Now you can use it
#include <iostream>
int main()
{
typedefint Array2x2[2][2];
Array2x2 a = {{0,1}, {2,3}}; // array
Array2x2* aptr = &a; // pointer to array
std::cout << (*aptr)[0][0] << '\n';
}
or just write it all at once:
1 2 3 4 5 6 7
#include <iostream>
int main()
{
int a[2][2] = {{0,1}, {2,3}};
int (*aptr)[2][2] = &a;
std::cout << (*aptr)[0][0] << '\n';
}
Your code declares int** a, which is a pointer to a pointer to an int, not a pointer to any array.
Seeing as you're trying to compile arry = a, it sounds like you're looking for a pointer to a row, which is what you get if you use a on the right side of assignment:
1 2 3 4 5 6 7
#include <iostream>
int main()
{
int a[2][2] = {{0,1}, {2,3}};
int (*arry)[2] = a; // or = &a[0];
std::cout << arry[0][0] << '\n';
}
What's your use case anyway, why do you need this?
This doesn't work because a "pointer to a pointer" is not the same thing as a "2D array". A 2D array is an array of arrays. Contrary to what you might think... arrays and pointers are not the same thing.
If you want a pointer to the actual 2D array:
1 2 3 4 5
int a[2][2] = {...};
int (*ptr)[2][2];
ptr = &a;
cout << (*ptr)[0][0]; // accessing elements
Note this requires the size of ALL dimensions be known.
Also note this does not work with dynamically allocated ("nested new") arrays.
If you want a pointer to the first 1D array in the 2D array
1 2 3 4 5 6 7 8
int a[2][2] = {...};
int (*ptr)[2];
ptr = &a[0];
// or
ptr = a;
cout << ptr[0][0]; // accessing elements
Note this requires the size of the 2nd dimension be known.
Also note this still does not work with 'nested new' arrays.
in case1 why i don't need & sign ? totally confused!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int a[3][3]={{0,1,2},{4,5,6}};
int (*ptr1)[3]=a; //case 1
cout<<(*ptr1)[2]<<endl;
int b[3]={7,8,9};
int (*ptr2)[3]=&b; //case2
cout<<(*ptr2)[2]<<endl;
return 0;
}
In the first case, ptr1 is an int*[], and a is int[][]. a can be converted to int*[] since the name of an array can decay to a pointer.
In the second case, ptr2 is an int*[] and b is an int[]. So while b can be converted to int*, that just points to an int and not to an array of ints like ptr2 expects. So you can use & to take the address of b (the address of an int[], which is an int*[]).