[英]Passing Dynamic Two Dimensional Array as argument to a functoin in c++
Hy guys, I actually Trying to create a 2D Array in c++ but not able to create that, When I execute the following statement嘿伙计们,我实际上试图在 C++ 中创建一个 2D 数组,但无法创建,当我执行以下语句时
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它给了我错误,当我在 google 上搜索时,它向我显示 C++ 中的 2D 数组是指针数组,其声明类似于以下语句
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我得到的逻辑是 a 是指向矩阵的指针,但现在我无法理解逻辑,例如如何指向该矩阵上的数据,假设看到索引
a[0][0]
的数字存储a[0][0]
我应该写吗
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.实际上我无法理解如何在矩阵中使用指向指针的指针,与其他语言相比,它太复杂了,我们只需要使用
new
运算符并可以使用它们的维度访问它们,不需要这个指向指针概念。 Please help me understanding the whole logic of this 2d dynamic array of c++.请帮助我理解这个 2d 动态 C++ 数组的整个逻辑。
you need to get the parameter in your function as pointer您需要将函数中的参数作为指针获取
void displayArray(int **a)
{
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 prints 10 rows and columns of value 0 because the 2D array is uninitialized它打印 10 行和值为 0 的列,因为二维数组未初始化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.