Issue with free();一个二维数组,其中一个在c中已知



我想释放();在使用malloc之后,一个二维数组,其中一个维度是已知的。让我们以数组psi[i][3]为例;我被要求数组类型为unsigned int,我不知道它的大小,所以我这样做了:

unsigned int (*psi)[3] = malloc(i * sizeof *psi);
if((psi)[3] == NULL ) {
printf("Error! memory not allocated.");
exit(0);
});

free(psi);
上面的问题是,虽然我已经将psi数组声明为上面的unsigned int,但我只在free中得到这个错误:
error 257 [Error] 'psi' undeclared (first use in this function)
我将感谢你的帮助,感谢你所有的时间!

Typedefs帮助很大。这是固定尺寸的内部尺寸:

typedef int three_ints[3];

现在你可以更容易地分配它们的动态数组:

three_ints * psi = malloc( nrows * sizeof(three_ints) );
if (!psi) {
complain();
}

并释放他们:

free( psi );

与任何2D数组一样,您可以使用通常的语法遍历它:

for (int row = 0;  row < nrows;  row++)
{
for (int col = 0;  col < 3;  col++)
printf( "t%d", psi[row][col] );
printf( "n" );
}

最新更新