我得到了一个足够大小的一维缓冲区 (int buffer[100]
)。我需要重新组织与二维数组相同的内存。我想要做的是将其类型转换为双指针 (int ** p
),然后将指针传递给将进行重组的 alloc 函数。函数返回后,我需要语句 p[2][2]
才能工作。
这是代码:
#include <stdlib.h>
#include <stdio.h>
void alloc(int ** buf, int r, int c)
{
int **temp;
temp=buf;
for(int i=0;i<r;i++)
buf[i]=*(temp+i*c);
}
void main()
{
int buffer[100];
int **p=(int **)buffer;
alloc(p, 4, 4);
p[2][2]=10;
printf("%d", p[2][2]);
}
上面的代码编译成功,但是当我运行代码时,我在执行语句时遇到访问冲突
p[2][2]=10;
我不明白问题出在哪里。 alloc函数有问题吗?或者是其他问题?
最佳答案
让我们检查您的代码以了解它为何不起作用。
让我们使用更短的缓冲区来了解您在做什么。
假设您有:
int buffer[9];
并且您想将其视为 3x3 二维数组。内存使用缓冲区:
buffer
|
v
+---+---+---+---+---+---+---+---+---+
| | | | | | | | | |
+---+---+---+---+---+---+---+---+---+
你想创建一个 int** p
这样:
p[0] p[1] [p2]
| | |
v v v
+---+---+---+---+---+---+---+---+---+
| | | | | | | | | |
+---+---+---+---+---+---+---+---+---+
为了实现这一点,您已分配内存来存储 p[0]
、p[1]
和 p[2]
。这意味着,您需要:
int** p = new int*[3];
p[0] = buffer;
p[1] = buffer + 3;
p[2] = buffer + 6;
现在,p
以及 p[0]
、p[1]
、p[2]
指向有效地址。您可以使用语法 p[m][n]
。
在我们的代码中,您刚刚指定 p
指向与 buffer
相同的位置,并通过使用语句
buf[i]=*(temp+i*c);
你只是把buffer
持有的内存当成了int*
的持有者,这不仅会破坏buffer
中的数据,还会使得指针的值不可预测。
这是一个工作程序。
#include <stdio.h>
int main()
{
int buffer[100];
int rows = 4;
int cols = 10;
int **p = new int*[rows];
for ( int i = 0; i < rows; ++i )
{
p[i] = buffer + i*cols;
printf("%p\n", p[i]);
for ( int j = 0; j < cols; ++j )
{
p[i][j] = i*2 + j*3;
}
}
printf("\n");
for ( int i = 0; i < rows; ++i )
{
for ( int j = 0; j < cols; ++j )
{
printf("%d ", p[i][j]);
}
printf("\n");
}
}
关于c++ - 将 1d 缓冲区重新组织为 2d 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23966654/