Hy guys, I actually Trying to create a 2D Array in c++ but not able to create that, When I execute the following statement
int arr=new int[10][10]
It gives me error and when I search on google it shows me 2D array in c++ is array of pointers which is declare like the below statements
int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];
I got the logic which is a is a pointer to pointer to the matrix but now I am not able understand the logic like how can i point to the data on this matrix, Suppose to see the number store in index a[0][0]
should i write
cout<<a[0][0]
or not, I am not able to get the logic how this pointer to pointer will work when with the pointers pointing to the matrix, and one more thing is that I am not able to pass it as an argument to a function. The code for passing it as a parameter is given below
void displayArray(int a[10][10])
{
for (int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
cout<<*a[i][j]<<"\t";
}
cout<<endl;
}
}
int main()
{
int** a = new int*[10];
for(int i = 0; i < 10; ++i)
a[i] = new int[10];
displayArray(**a);
}
It giving me the following error
error: invalid conversion from ‘int’ to ‘int (*)[10]’ [-fpermissive]
Actually I am not able to get any sense of how to use the pointer to pointer in a matrix, it's too complex compared to other languages where we just need to use new
operator and can access them with their dimensions, No need of this pointer to pointer concept. Please help me understanding the whole logic of this 2d dynamic array of c++.
you need to get the parameter in your function as pointer
it prints 10 rows and columns of value 0 because the 2D array is uninitialized