分配和使用无效用C免费二维数组 [英] Allocate and free 2D array in C using void
本文介绍了分配和使用无效用C免费二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
的想法是仅使用两个功能,可以既分配和未在编译时已知的给定数据类型的分类的2D阵列。在code我在释放函数编写崩溃,但我不明白为什么。这里是code:
The idea is to use only two functions that can both allocate and free a 2D array of a given data type that is not known at compile-time. The code I have written crashes in the freeing function, but I cannot see why. Here is the code:
void** new2DArray(int row, int col, int typeSize){
void** temp = malloc(sizeof(void*)*row); //EDIT
for (row-=1; row >= 0; row--)
temp[row] = malloc(typeSize*col);
return temp;
}
void free2DArray(void** array, int row, int typeSize){
for (row -= 1; row >= 0; row--)
free( *(array + row*typeSize) );
free(array);
}
在哪里,对于一个3x3阵列,是会被称为这样的:
Where, for a 3x3 array, is would be called like:
double** test = (double**) new2DArray(3, 3, sizeof(double));
free2DArray(test, 3, sizeof(double));
这有什么错,立即与释放功能?
Is there anything immediately wrong with the freeing function?
推荐答案
的 free2DArray
看起来是错误的。不需要知道类型的大小;你只需释放你分配的块:
The free2DArray
looks wrong. You don't need to know the size of the types; you just free the blocks that you allocated:
void free2DArray(void** array, int row){
for (row -= 1; row >= 0; row--)
free( array[row] );
free(array);
}
这篇关于分配和使用无效用C免费二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文