gpt4 book ai didi

c - 函数指针和函数名的区别

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:08 25 4
gpt4 key购买 nike

什么是函数名?它与指向它的指针有什么关系?为了理解这些问题,编写了以下代码:

#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;
}

输出如下:

output of the program

在代码中,定义了一个简单的函数testFunc,并有一个指针p_testFunc指向它。我在网上了解到,我尝试了四种调用这个函数的方法,它们都有效,虽然我不是很明白。

接下来的两行试图弄清楚函数名和它的指针到底是什么。我能理解的一件事是 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);

我还注意到在您的代码中您没有使用任何 &。考虑以下片段的结果:

    #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 将格式化您输入内容的地址。

关于c - 函数指针和函数名的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44330517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com