所以我创建了 2 个函数来将元素添加到二维数组,然后释放它。该数组是 n x 2。每次 n=n+1 时,我都使用 realloc 分配额外的空间。这是我的代码:
void add_cell(int** table, int value1,int value2,int elements_count){
table=(int**)realloc(table, sizeof(*table) * (elements_count+1)); //<--I think this may be problematic
table[elements_count]=(int*)malloc(2*sizeof(table[elements_count]));
table[elements_count][0]=value1;
table[elements_count][1]=value2;
}
void reset_table(int** table,int elements_count){
int i;
for(i=0;i<elements_count;i++){
free(table[i]);
}
printf("reset done");
}
当我添加额外的单元格时,我每次只添加 1 个额外的行。所以 2x2 数组变成 3x2,3x2 变成 4x2,所以如果我这样调用:
add_cell(coord_table,5,4,3);
before after
1 2 1 2
2 3 -> 2 3
3 4 3 4
4 5
这就是我调用函数的方式(这段代码确实有任何目的,它只是为了测试函数):
int main(){
int **coord_table;
int i;
for(i=0;i<5;i++){
add_cell(coord_table,i+1,i+2,i);// should allocate 1extra row each time so
//when i=0 you should have [1 2]
//when i=2 [1 2][2 3]
//when i=3 [1 2][2 3][3 4] and so on...
}
reset_table(coord_table,5);
for(i=0;i<5;i++){
add_cell(coord_table,i+1,i+2,i);
}
reset_table(coord_table,5);
free(coord_table);
return 0;
}
我对使用带 malloc 和 realloc 的二维数组有点陌生,我什至不知道这是否是做我想做的事情的好方法,但这是我想出的。但是当它试图调用 reset_table 时它总是崩溃。我相信我使用 realloc 错误地分配了表,即使它在尝试释放时崩溃,而不是在分配时崩溃。
任何想法都有帮助,提前致谢:)
最佳答案
重新分配引用对象的大小乘以所需元素的数量。部分问题是名称选择不当。 elements_count 不是元素的个数,而是最后一个元素的索引。
不需要强制转换。
需要返回重新分配的表
,否则main()
将看不到新值。
int** add_cell(int** table, int value1,int value2,int last_element_index){
// table=(int**)realloc(table,sizeof(table)+sizeof(int**));
table= realloc(table,sizeof *table) * (last_element_index + 1));
// Better code would check for allocation success here.
// table[elements_count]=(int*)malloc(2*sizeof(table[elements_count]));
table[elements_count]=malloc(sizeof *table[elements_count] * 2);
table[elements_count][0]=value1;
table[elements_count][1]=value2;
return table;
}
不需要原来的分配。
int main(void) {
// int **coord_table=(int**)malloc(1*sizeof(int*));
int **coord_table = NULL;
int i;
for(i=0;i<5;i++){
coord_table = add_cell(coord_table,i+1,i+2,i);
}
reset_table(coord_table,5);
for(i=0;i<5;i++){
coord_table = add_cell(coord_table,i+1,i+2,i);
}
reset_table(coord_table,5);
free(coord_table);
return 0;
}
细节
int** table
不是二维数组。它是一个指针。 table as pointer to pointer to int . int a[3][4]
是二维数组或 array 3 of array 4 of int 的示例
关于c - 通过 c 中的函数添加和释放二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55035519/