【发布时间】:2026-01-06 18:10:02
【问题描述】:
我正在尝试创建一个获取列数和行数(宽度和高度)的函数,构建一个二维矩阵,然后将 Matrix[0][0] 的地址返回给原始调用者中的指针-函数。
int **allocateMatrix(int width, int height) // function that allocate
//memory for 2D matrix and check that memory allocation was successful
{
int **Matrix;
int row;
Matrix = (int**)malloc(sizeof(int*)*height);
if (!Matrix)
{
printf("failed to allocate memory. this program is over.\n");
exit(1);
}
for (row = 0; row < height; row++)
{ Matrix[row] = (int*)malloc(sizeof(int)*width);
if (!Matrix[row])
{
printf("failed to allocate memory. this program is over.\n");
exit(1);
}
}
return Matrix;
}
在分配过程中,我通过调试器观察了整个事情,它似乎创建了一个我想要的太大的矩阵,并且通常是一种意想不到的行为。 如:高=5,宽=5, 虽然 Matrix[0][30] - 存在且可达。
此外,我不确定我返回的地址。
【问题讨论】:
-
@Ofer Bar Oz,你希望
Matrix[0][30]做什么?您是否期望 C 能够发现编码错误? -
由于
void *被自动提升,因此无需转换 malloc 的结果 -
建议将
Matrix[row] = calloc (width, sizeof *Matrix[row])分配为calloc将在Matrix[row]初始化所有元素0中的所有字节归零,以防止在无意中访问未初始化元素时出现未定义行为。
标签: c function pointers memory malloc