我正在尝试编写 2 个函数,一个用于动态分配二维数组,另一个用于释放此二维数组:
int allocate(int **array, unsigned int rows, unsigned int columns){
int i;
for (i = 0; i < rows; i++) {
array[i] = malloc(columns * sizeof (int));
}
/* Code fo fill the array*/
return 1;
}
void de_allocate(int **v, unsigned int rows) {
int i;
for (i = 0; i < rows; i++) {
free(v[i]);
}
free(v);
}
int main(int argc, char **argv) {
int rows, columns;
rows = atoi(argv[1]);
columns = atoi(argv[2]);
int *ipp[rows];
allocate(ipp, rows, columns);
de_allocate(ipp,rows);
return 0;
}
我必须尊重分配函数签名:
int allocate(int **array, unsigned int rows, unsigned int columns)
并且在分配函数结束时,ipp 必须能够访问分配的二维数组。
分配函数是正确的,但在 de_allocate 函数中我有一个 SIGABRT 信号
最佳答案
问题是您正在尝试使用代码 free(v);
如果分配了指针数组,您可以这样做,但是您在 main
函数中使用 int *ipp[rows];
如果您想保留 de_allocate,请将其更改为 int **ipp = malloc(sizeof(int*)*rows);
。
你可以测试一下
#include <stdio.h>
#include <stdlib.h>
int allocate(int **array, unsigned int rows, unsigned int columns){
int i;
for (i = 0; i < rows; i++)
{
array[i] = malloc(columns * sizeof (int));
}
/* Code fo fill the array*/
return 1;
}
void de_allocate(int **v, unsigned int rows) {
int i;
for (i = 0; i < rows; i++)
{
free(v[i]);
}
free(v);
}
int main(int argc, char **argv)
{
int rows, columns;
int temp = 0;
rows = atoi(argv[1]);
columns = atoi(argv[2]);
int **ipp = malloc(sizeof(int*)*rows);
allocate(ipp, rows, columns);
for (int i=0; i<rows; i++)
for (int j=0; j<columns; j++)
ipp[i][j] = temp++;
for (int i=0; i<rows; i++)
for (int j=0; j<columns; j++)
printf("ipp[%d][%d] = %d\n", i, j, ipp[i][j]);
de_allocate(ipp,rows);
return 0;
}
关于c- 分配和释放二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33035371/