我给了一个int buffer[100]足够大小的1d缓冲区().我需要重新组织与2d数组相同的内存.我想要做的是将它转换为双指针(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]);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码编译成功,但是当我运行代码时,我在执行语句时得到访问冲突
p[2][2]=10;
Run Code Online (Sandbox Code Playgroud)
我无法理解问题所在.alloc函数有问题吗?或者是其他问题?