指针类型不兼容

Bof*_*fin 9 c gcc

我有以下签名的功能:

void box_sort(int**, int, int)
Run Code Online (Sandbox Code Playgroud)

和以下类型的变量:

int boxes[MAX_BOXES][MAX_DIMENSIONALITY+1]
Run Code Online (Sandbox Code Playgroud)

当我调用该函数时

box_sort(boxes, a, b)
Run Code Online (Sandbox Code Playgroud)

海湾合作委员会给了我两个警告:

103.c:79: warning: passing argument 1 of ‘box_sort’ from incompatible pointer type (string where i am calling the function)
103.c:42: note: expected ‘int **’ but argument is of type ‘int (*)[11] (string where the function is defined)
Run Code Online (Sandbox Code Playgroud)

问题是为什么?int x [] []和int**x(实际上是int*x [])是不是C中的相同类型?

Cas*_*bel 13

我知道几天前有一个几乎完全像这样的问题......但是现在找不到它.

答案是,int[size][](见底部注释)并且int**绝对不是同一类型.在许多情况下,您可以使用int[]int*互换,特别是在这种情况下,因为当您将数组传递给函数时,数组会衰减到指向第一个元素的指针.但对于二维数组,这些是非常不同的存储方法.

这是他们在内存中看起来像2x2阵列的样子:

int a[2][2]:

__a[0][0]__|__a[0][1]__|__a[1][0]__|__a[1][1]__
  (int)       (int)       (int)       (int)

int **a (e.g. dynamically allocated with nested mallocs)

__a__
(int**)
  |
  v
__a[0]__|__a[1]__
  (int*)  (int*)
    |        |
    |        |
    v        ------------------>
__a[0][0]__|__a[0][1]__        __a[1][0]__|__a[1][1]__
  (int)       (int)              (int)       (int)
Run Code Online (Sandbox Code Playgroud)

你可以像这样构建第二个:

int **a = malloc(2 * sizeof(int*));
a[0] = malloc(2 * sizeof(int));
a[1] = malloc(2 * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

注意:正如其他人所说,int[][]不是真正的类型; 只有一种尺寸可以不指定.但问题的核心是二维数组和双指针是否相同.

  • NomeN:这是因为它没有意义 - 你可以合理地将数组转换为指向其第一个元素的指针,因为数组只是一系列连续元素; 但你*不能*合理地将数组数组转换为指向指针的指针,因为指向指针的指针必须指向*指针(s),并且没有它指向的实际指针.咳咳. (2认同)