[英]c++ 2d array and pointer references
In the following code when arr is passed to transpose function as below and inspect the contents of a as a[0], it is giving 0x00...001 but not the original address as inspected for arr , why it is so and what is wrong ?. 在下面的代码中,将arr传递给如下的转置函数并以a [0]的形式检查a的内容时,它给出的是0x00 ... 001,而不是arr所检查的原始地址,为什么这样,是什么?错了吗? I expect a[0] to be the address of 1 in the array and a[0][1] to be the first element of the array.
我期望a [0]是数组1的地址,而a [0] [1]是数组的第一个元素。 Please explain.
请解释。
problem: 问题:
int arr[][4] = { { 1, 2, 3, 4},{ 5, 6,7,8 },{ 9,10,11,12 } };
transpose((int **)arr, 3, 4);
int** transpose(int** a, int m, int n)
{
int** output = new int*[n];
for (int i = 0;i < m;i++)
{
output[i] = new int[n];
}
for (int i = 0;i < m;i++)
{
for (int j = 0;j < n;j++)
{
//*((output[j]) + i) = *(a[i] + j);
//*((output[j]) + i) = a[i][j];
output[j][i] = a[i][j];
}
}
return output;
}
throwing exception. 引发异常。
works fine: 工作正常:
int** output=transpose((int *)arr, 3, 4);
print(output,3,4);
int**transpose(int * a, int m, int n)
{
int** t = new int*[n];
for (int i = 0;i < n;i++)
{
t[i] = new int[m];
}
for (int i = 0;i < m;i++)
{
for (int j = 0;j < n;j++)
{
t[j][i] = *((a + i*n) + j);
}
}
return t;
}
void Matrix::print(int ** a, int m, int n)
{
for (int i = 0;i < m;i++)
{
for (int j = 0;j < n;j++)
{
std::cout << a[i][j] << ",";
}
std::cout << "\n";
}
}
In order for your code to work with a 2 dimensional array, the code should be modified such as shown below. 为了使您的代码与二维数组一起使用,应修改代码,如下所示。
int arr[3][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
transpose(&arr, 3, 4);
int** transpose( int(*a)[3][4], int m, int n)
{
int** output = new int*[n];
for (int i = 0; i < m; i++)
{
output[i] = new int[n];
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
//*((output[j]) + i) = *(a[i] + j);
//*((output[j]) + i) = a[i][j];
if (i < n && j < m )
{
output[j][i] = (*a)[i][j];
}
}
}
return output;
Look at the parameter declaration int(*a)[3][4]
. 查看参数声明
int(*a)[3][4]
。 It says that the variable a
is a pointer to a 2-dimensional array of size [3][4]. 它说变量
a
是指向大小为[3] [4]的二维数组的指针。 An additional check if (i < n && j < m )
ensures that the array access won't go out of bounds. 额外检查
if (i < n && j < m )
确保数组访问不会超出范围。
It would work without any exception! 它将毫无例外地工作!
First of all in your example m is 3 and n is 4, so in transpose function you are creating output with n (4) pointers but then you have for loop from 0 to m (3), so at this point output already has uninitialized element (output[3]). 首先,在您的示例中, m为3, n为4,因此在转置函数中,您将使用n (4)个指针创建输出,但随后您需要从0到m (3)的for循环,因此,此时输出已未初始化元素(输出[3])。 The reason why it crashes is that you use that uninitialized element in next loops.
它崩溃的原因是您在下一个循环中使用了该未初始化的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.