繁体   English   中英

函数指针和函数名之间的区别

[英]difference between function pointer and function name

什么是功能名称? 它与指针的关系是什么?为了尝试理解这些问题,下面的代码是:

#include <stdio.h>

int testFunc(void);

void ptrFuncProp(void);

int main(){
    ptrFuncProp();
    return 0;
}

void ptrFuncProp(void){
    int i = 0;
    int (*p_testFunc)(void) = testFunc;

    testFunc();
    (*testFunc)();
    p_testFunc();
    (*p_testFunc)();

    printf("testFunc:\t%d\n*testFunc:\t%d\n",sizeof(testFunc),sizeof(*testFunc));
    printf("p_testFunc:\t%d\n*p_testFunc:\t%d\n",sizeof(p_testFunc),sizeof(*p_testFunc));
    putchar('\n');

    printf("testFunc:\t%c\n",testFunc);
    printf("*testFunc:\t%c\n",*testFunc);
    printf("*p_testFunc:\t%c\n",*p_testFunc);

    for(;*p_testFunc && i<30;i++){
        printf("%c ",*(p_testFunc + i));
        if(i%10 == 9){
            putchar('\n');
        }
    }
}

int testFunc(void){
    int i=0;
    printf("output by testFunc\n");
    return 0;
}

输出如下:

程序的输出

在代码中,定义了一个简单的函数testFunc,并且指针p_testFunc指向它。正如我在互联网上学到的,我尝试了四种方法来调用这个函数;它们都可以工作,尽管我并不完全理解。

接下来的2行尝试弄清楚究竟是什么函数名称和它的指针。我能理解的一件事是p_testFunc是一个指针,所以它包含其他东西的地址;地址是8个字节。 但是为什么函数名的大小是1个字节,因为我曾经认为函数名是一个const指针,其内容是函数开头的地址。 如果函数名称不是指针,它怎么能被解除引用?

实验结束后,问题仍然没有解决。

如果你刚进入C,你应该掌握首先是什么指针。

指针是一个变量,其值是另一个变量的地址,即内存位置的直接地址。与任何变量或常量一样,必须在使用它来存储任何变量地址之前声明指针 ”。

指向整数/字符等的指针与指向函数的指针之间没有区别。 其目的是指向存储器中的地址,在这种情况下,存储该功能。

另一方面,函数的名称就是函数的命名方式。 正如人们在评论中建议的那样,它标识了编译器,链接器前面的函数。

如何定义函数:

int ( what the function will return) isEven (the function name) (int number) ( what argument will it accept)
//How it would look like
int isEven (int number){

   //Here goes the body!

}

只是对功能的一点概述。

如何定义指针函数:

int (return type) *(*isEven(Name))(int(input arguments));
//No tips again!
int  (*isEven)(int);

另外我在你的代码中注意到你没有使用任何&。 考虑以下snipet的结果:

    #include <stdio.h>
void my_int_func(int x)
{
    printf( "%d\n", x );
}

int main()
{
    void (*foo)(int);
    /* the ampersand is actually optional */
    foo = &my_int_func;
    printf("addres: %p \n", foo);
    printf("addres: %p \n",  my_int_func);


    return 0;
}

注意:%p将格式化您输入的地址。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM