提问者:小点点

函数名是C语言中该函数第一条指令的地址吗?


为什么编译器说这不是指针:

#include <stdio.h>

double f(){ return 1.2; }
int main(){

    int i=0;
    double d =f()[0]; //f() is not pointer? it should be
    printf("%i\n",d);
}

错误:

subscripted value is neither array nor pointer nor vector
  double d =f()[0];

而是我已经声明了一个函数指针,然后用了一个函数的名字,那么它就会变成指针:

#include <stdio.h>

int op(int (*op)(int,int), int a, int b){ return op(a,b); }
int add(int a, int b){ return a+b; }

int main(){
    printf("%i\n",op(add, 1, 2)); //here: add() will magically become pointer, different context
}

所以在第一种情况下,我想取消引用函数,在hope中,函数的名称是pointer(因此取消引用是允许的)。 在第二个示例中,函数指针是用指针声明的,因此函数add将衰减为指针(与printf(“%i\n”,op(&add,1,2)))也将工作。 为什么第一个有问题?


共1个答案

匿名用户

对于函数f,或者通常是可调用的,f()调用该函数并计算为声明为函数返回类型的类型。 函数可以衰减为指向函数的指针,类似于数组,但当您调用函数时,这种情况不会发生:

int foo(int,int){ return 1;}

int main() {
    using fptr = int (*)(int,int);
    fptr p = foo;                    // <- function pointer (note: no & needed because it decays to function pointer)
    fptr q = &foo;                   // <- also function pointer
    int x = foo(1,2);                // <- function call
}

在您的示例中:

double d =f()[0]; //f() is not pointer? it should be

否,f()不是指针。 F返回双精度。

printf("%i\n",op(add, 1, 2)); //here: add() will magically become pointer, different context

不会。add()不会神奇地变成指针。 add是将自动衰减到函数指针的函数(实际上它不是那么“神奇”)。

相关问题