不兼容的指针类型 [英] Incompatible pointer type

查看:112
本文介绍了不兼容的指针类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下签名的功能:

void box_sort(int**, int, int)

和以下类型的变量:

int boxes[MAX_BOXES][MAX_DIMENSIONALITY+1]

当我打电话功能

box_sort(boxes, a, b)

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

GCC gives me two warnings:

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)

问题是的为什么的?是否INT×〔] []和INT ** X(实际上为int * X [])不相同类型的C 2

The question is why? Whether int x[][] and int** x (and actually int* x[]) are not the same types in C?

推荐答案

我知道有一个问题几乎完全是这样几天前...不能找到它现在虽然。

I know there was a question almost exactly like this a couple days ago... can't find it now though.

答案是, INT [大小] [] (见注在底部)和 INT ** 绝对不是同一类型。您可以使用 INT [] 为int * 互换在很多情况下,特别是在这样的情况下,因为数组衰变一个指针,当你将它传递到一个函数的第一个元素。但对于一个二维阵列,这些都是存储的非常不同的方法。

The answer is, int[size][] (see note at the bottom) and int** are definitely not the same type. You can use int[] and int* interchangeably in many cases, in particular in cases like this because the array decays to a pointer to the first element when you pass it into a function. But for a two-dimensional array, these are very different methods of storing.

下面是他们什么样子在内存中一个2x2的阵列:

Here's what they'd look like in memory for a 2x2 array:

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)

您可以构造第二个是这样的:

You could construct the second one like this:

int **a = malloc(2 * sizeof(int*));
a[0] = malloc(2 * sizeof(int));
a[1] = malloc(2 * sizeof(int));

请注意:正如其他人指出, INT [] [] 不是一个真正的类型;只有尺寸之一可以不指定。但这里的问题的核心是一个二维阵列和双指针是否是同一个东西。

Note: As others have noted, int[][] isn't a real type; only one of the sizes can be unspecified. But the core of the question here is whether a two-dimensional array and a double pointer are the same thing.

这篇关于不兼容的指针类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆