![](/img/trans.png)
[英]Why can't I pass the address of a pointer to a fixed size array into a function expecting a pointer to a pointer in C?
[英]Can't pass address to pointer
我已经编写了一个简单的测试程序来访问和递增存储在正确运行的内存地址中的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;
}
&latestint
是int **
而insert()
期望是int *
。
至于为什么它可以正确运行,编译器将int **
隐式转换为int *
, 因此latestint
的地址传递给insert()
,其值为0,因此您会巧合地得到输出。 表格可以清楚地说明这一点。
+------------+------------+--------+-----------+
| Address | Value | Type | label |
+------------+------------+--------+-----------+
| 0x12345678 | 0x00000000 | int * | latestint |
| whatever | 0x12345678 | int ** | &latestint|
+------------+------------+--------+-----------+
latestint
是指向int的指针。 将其更改为int
类型。
在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 *”。
(您也可以修改“插入”,以便它等待一个int **。我想这不是您想要执行的操作,结果可能令人惊讶)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.