【问题标题】:Initialisation from incompatible pointer type warning. Can't find the issue从不兼容的指针类型警告初始化。找不到问题
【发布时间】:2010-12-28 17:04:07
【问题描述】:

我假设这个警告会使我的应用程序崩溃。我正在将 Objective-c 用于 iOS 应用程序。 Xcode 不提供堆栈跟踪或任何东西。没有帮助。

我将此赋值作为全局变量:

int search_positions[4][6][2] = {{{0,-2},{0,1},{1,-1},{-1,-1},{1,0},{-1,0}}, //UP
    {{-2,0},{1,0},{-1,1},{-1,-1},{0,1},{0,-1}}, //LEFT
    {{0,2},{0,-1},{1,1},{-1,1},{1,0},{-1,0}}, //DOWN
    {{2,0},{-1,0},{1,1},{1,-1},{0,1},{0,-1}} //RIGHT 
};

因此,search_positions 不是指向整数指针的指针吗?

为什么会出现“从不兼容的指针初始化”?

int ** these_search_positions = search_positions[current_orientation];

当然这只是从数组中获取一个指向整数指针的指针,由 current_orientation 偏移?

我在这里缺少什么?我以为我现在知道指针了。 :(

谢谢。

【问题讨论】:

    标签: c arrays pointers multidimensional-array double-pointer


    【解决方案1】:

    search_positions[current_orientation] 不是int** 类型;它的类型为int[6][2]search_positions 不是指针;它是一个数组。

    如果您获取数组的地址,则指向search_positions[current_orientation] 的指针将是int(*)[6][2] 类型:

    int (*these_search_positions)[6][2] = &search_positions[current_orientation];
    

    或者int(*)[2]类型,如果你不获取数组的地址,而是让数组到指针的转换发生:

    int (*these_search_positions)[2] = search_positions[current_orientation];
    

    【讨论】:

    • 好的,谢谢。我想我现在记得......如果数组只是指针会更容易。你可以通过指针来做数组(想想malloc),为什么不能反过来呢?
    • @Matthew Mitchell:数组只是指针。这是 C 的基本事实。如果您希望它们相同,则意味着放弃其中一个。你更喜欢哪一个:没有指针或没有数组?我认为不使用任何一种都会导致语言严重瘫痪。
    • 你可以有一个指向数组的指针(显然不是数组。也许是一组?)进一步的指针或一些数据。你可以用 malloc 做到这一点。您可以使用相同的方括号语法访问这些指针数组或任何其他内容中的数据。这让我更加困惑。
    • @Matthew:是的,数组和指针之间的关系在第一次学习 C 的时候有点混乱。是的,如果数组或指针的定义不同,它会不会那么混乱。然而,C 就是这样,我们可以接受它:-)
    • 除了 int (*these_search_positions)[2] 语法之外,现在一切都说得通了。不知道如何定义一个指向 2 个整数数组的指针。
    【解决方案2】:

    指针不是数组,数组不是指针

    search_positions 被定义为“4 个数组,6 个数组,2 个 ints”。这使得search_positions[current_orientation] 成为“6 个数组,每组 2 个 ints”。
    该数组可以隐式转换为指针,但这只会给您一个指向 2 个ints (int (*)[2]) 数组的指针。这是与您使用的“指向int 的指针”不同的类型,并且两者之间没有合适的转换。

    要解决这个问题,您可以将these_search_positions 声明为

    int (*these_search_positions)[2] = search_positions[current_orientation];
    

    【讨论】:

    • 好的,谢谢。那么我可以将数组的第一级转换为整数数组的指针吗?我会尽量记住这一点以及您发布的我无法理解的语法。
    猜你喜欢
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2021-06-27
    • 2011-09-01
    相关资源
    最近更新 更多