gpt4 book ai didi

c++ - 双指针和二维数组有什么关系?

转载 作者:行者123 更新时间:2023-11-28 01:04:57 25 4
gpt4 key购买 nike

void displayMatrix(int **ptr)
{
printf("%d %d \n",**ptr,*(*ptr+1));
*ptr++;
printf("%d %d \n",**ptr,*(*ptr+1));
}

将 2x2 数组传递给函数是否正确?

displayMAtrix(array); 

最佳答案

如果您有一个具有自动存储持续时间的二维数组(例如 int matrix[2][2];),那么,这不是正确的方法传递一个二维数组。

int f ( int, char ** )
{
int matrix[2][2];
displayMatrix(matrix);
}

要符合标准(还有其他方法可以使其工作,但这是标准的推荐方法),您需要将 displayMatrix() 声明为:

void displayMatrix ( int matrix[][2] );

您必须声明每个维度的大小(可能不包括第一个维度)。这背后的原因在于二维数组在内存中的存储方式。维基百科在 row-major order 上有一篇不错的文章解释布局。

备用存储类型

如果您正在分配大型矩阵(例如用于存储图像),您通常会以双指针结束,因为您将以不同方式分配内存。在这种情况下,您通常有一个一维指针数组,每个项目都存储指向表示行(或列)的一维数组的指针。

在那种情况下,你会得到类似的东西:

// this function is over-simplified.  it may leak memory if any
// but the first `new` throws `std::bad_alloc`.
int ** new_matrix ( int m, int n )
{
int ** matrix = new int*[m];
for (int i = 1; (i < m); ++i ) {
matrix[i] = new int[n];
}
return (matrix);
}

void displayMatrix ( int ** matrix, int m, int n );

int main ( int, char ** )
{
int **const matrix = new_matrix(2, 2);
displayMatrix(matrix, 2, 2);
}

关于c++ - 双指针和二维数组有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6763627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com