c- 分配和释放二维数组

标签 c arrays pointers sigabrt

我正在尝试编写 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);

释放堆栈分配的 var

如果分配了指针数组,您可以这样做,但是您在 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/

相关文章:

c - 骨架代码 : character pointers struggles

c - 创建单链表时出现异常

c - clang 和 gcc 之间的行为差​​异?

C:如何从函数返回数字数组

javascript - Firestore 更新数组字段中的单个项目

c++ - 简单指针对象错误C++

将二进制转换为十六进制

c - 为什么 64 位 Visual Studio C 中的 CreateWindow 在创建时会自行销毁?

ruby-on-rails - Ruby 数组等效于 active record.where(criteria)

php - 查询数据库以取回数组