为什么不能在 C 语言的函数中创建类似于我下面的数组?
int **image;
int height, weight;//initialized in a method not shown
void generateMatrices()
{
image = (int **)malloc(sizeof(int*) * height);
if(image == NULL)
{
fprintf(stderr, "Image matrix could not be made\n");
exit(-1);
}
int y;
for(y = 0; y < height; y++)
{
image[y] = (int *)malloc(sizeof(int) * width);
if(image[y] == NULL)
{
fprintf(stderr, "Image matrix row %d could not be made\n", y);
exit(-1);
}
}
}
int main(int argc, char* argv[])
{
generateMatrices();
image[height-2][width-2] = 90;//Fails here
return 0;
}
首先,我为提出这个不清楚的问题表示歉意。澄清一下,我确实知道如何制作这些矩阵,而且事实上,它确实有效。然而,所有这些代码最初都在我的主语句中,我想通过将其放入各种方法中来重构我的代码。其中一种方法名为generateMatrices()。由于某种原因,即使矩阵被认为是全局的,并且即使在它们存在的方法内,当我尝试从该方法外部访问它们时,例如紧接着在 main 中访问它们时,我会遇到段错误。
再次编辑以进一步澄清代码。
事实证明这段代码确实有效,而且我显然正在初始化 height
和width
之后我调用了这个方法。浪费大家的时间是我的错。
最佳答案
编辑后,二维分配看起来不错。 height
和 width
的值可能出错了。我尝试了你的例子here对于适当的 height
和 width
值,它可以正常工作
关于在 C 函数中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11019557/