【问题标题】:Can't pass address to pointer无法将地址传递给指针
【发布时间】:2014-04-10 15:24:19
【问题描述】:

我制作了一个简单的测试程序来访问和递增存储在内存地址中的 int,它运行正确,并在运行时输出 1,但是当我完成它时,我得到一个 warning 说以下内容:warning: passing argument 1 of ‘insert’ from incompatible pointer type 但是,我看不出问题出在哪里,因为我将一个地址传递给insert,它被声明为接受一个指针。

#include <stdio.h>

static void insert(int *nextfreeplace) {
        (*nextfreeplace)++;
        printf("%i\n", *nextfreeplace);

}
int main() {
        int * latestint = 0;
        insert(&latestint);
        return 0;
}

【问题讨论】:

    标签: c pointers memory-address


    【解决方案1】:

    &amp;latestintint **insert() 需要 int *
    至于为什么正确运行,编译器将int **隐式转换为int *所以latestint的地址传递给insert(),它的值为0,所以你得到巧合的输出。一张表格可以清楚地说明这一点。

    +------------+------------+--------+-----------+
    |  Address   |   Value    |  Type  |   label   |
    +------------+------------+--------+-----------+
    | 0x12345678 | 0x00000000 | int *  | latestint |
    | whatever   | 0x12345678 | int ** | &latestint|
    +------------+------------+--------+-----------+
    

    【讨论】:

    • @AkshaiShah:它运行正常,因为你运气不好。但是编译器告诉你不要相信可执行文件!
    【解决方案2】:

    latestint 是一个指向 int 的指针。将其更改为int 类型。

    【讨论】:

      【解决方案3】:

      在 C 语言中,指针是一个变量。和任何变量一样,每个指针都有一个类型。在您的代码中,变量“latestint”是“int”类型的指针:

      int * latestint = 0;
      

      值也有它们的类型(5 是 int,'a' 是 char,等等)。表达式“&latestint”是变量“latestint”的地址。这个地址是一个值(一个数字)。由于“latestint”是一个指针(一个包含另一个变量地址的变量),“&latestint”是一个指针(一个int指针)的地址,所以“&latestint”的类型是int**。

      然后,当您将 &latestint 传递给函数“insert()”时,编译器会告诉您“&latestint”是 int** 类型,但函数“insert()”等待一个 int*。

      您只需删除“latestint”声明中的“*”,然后“&latestint”的类型将为“int *”。

      (你也可以修改“insert”,让它等待一个int**。我猜这不是你想做的,结果可能会令人惊讶)

      【讨论】:

        猜你喜欢
        • 2020-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多