c - 我无法编译带有动态二维数组和指针的 C 文件

标签 c arrays pointers malloc

编辑:是的,我知道我已经有一个 3x100 阵列,无需执行所有这些操作。但问题是我不知道数组的大小,它会根据情况而变化。这就是为什么我想让它变得动态。

编译时我收到此警告:

c1.c:24:12: warning: assignment from incompatible pointer type >[-Wincompatible-pointer-types] copieTab = tabClef;

显然copieTabtabClef不兼容,因此无法为其分配值。

我创建了一个 3 行 100 列的动态 2D 数组。这是我的代码:

void allocation(size_t longClef, int copieTab[3][100]) {
  int i=0;
  int ** tabClef = NULL;
  tabClef = malloc(longClef * sizeof(char));

  if (tabClef == NULL) //Si l'allocation a echoue
  {
    printf("Allocation a echoue\n");
    return; // On arrete immediatement le programme
  }
  // On peut continuer le programme normalement sinon

  // Creer matrice
  for (i=0; i<longClef; i++) {
    tabClef[i] = malloc(100 * sizeof(char));
  }

  /* Copie du tableau dans un pointeur pour le sortir de la fonction */
  copieTab = tabClef;
}

最佳答案

the issue is that I don't know what size the array will be

OP 的代码是一个很好的尝试,但非常不适合分配 2D 动态大小的数组。

分配一个 row int * 指针数组。
row 次,分配一个 col int 数组。
返回第一步的指针。

int **alloc_2D_dynamic_int(size_t row, size_t col) {
  int **table = malloc(sizeof *table * row);
  if (table == NULL) Oops();  // TBD error handling
  for (size_t r = 0; r < row; r++) {
    table[r] = malloc(sizeof *(table[r]) * col);
    if (table[r] == NULL) Oops();
  }
  return table;
}

释放时,相反的步骤。

void free_2D_dynamic_int(int **table, size_t row) {
  if (table) {
    for (size_t r = 0; r < row; r++) {
      free(table[r]);
    }
    free(table);     
  }
}
<小时/>

否则OP可能想要为2D数组分配内存

void alloc_2D_int(size_t row, size_t col, int (**table)[row][col]) {
  *table = malloc(sizeof(**table));
}

或者返回分配的指针

void *alloc_2D_int_R(size_t row, size_t col) {
  int (*table)[row][col] = malloc(sizeof *table);
  return table;
}

关于c - 我无法编译带有动态二维数组和指针的 C 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48121073/

相关文章:

c - "const void * const *"在 C 中是什么意思?

c# - 为什么我不能在数组上调用 RemoveAt?

c++ - 创建动态多维数组

c - 堆损坏 - 调试断言失败。在 dbgheap.c 行 1322 表达式 _crtIsValidHeapPointer(pUserData)

c - 在结构中分配内存时类型不兼容

c - C FAQ 中引用了哪些书籍?

c++ - 使用自动工具和替代工具的优势

C 的上下文无关文法

arrays - 如何找到 [L, R] 之间大小的最大和子数组

c - 为什么我的 free() 包装函数不起作用?