什么是函数名称?它与指针的关系是什么?要尝试理解这些问题,下面的代码是编写的:
#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%dn*testFunc:t%dn",sizeof(testFunc),sizeof(*testFunc));
printf("p_testFunc:t%dn*p_testFunc:t%dn",sizeof(p_testFunc),sizeof(*p_testFunc));
putchar('n');
printf("testFunc:t%cn",testFunc);
printf("*testFunc:t%cn",*testFunc);
printf("*p_testFunc:t%cn",*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 testFuncn");
return 0;
}
输出如下:
程序的输出
在代码中,定义了一个简单的函数testfunc,一个指针p_testfunc指向它。当我在Internet上学到的时,我尝试了四种调用此功能的方式;尽管我不完全理解,但它们都起作用。<<<<<<<</p>
接下来的2行尝试找出真正的函数名称和一个指针。我可以理解的是p_testfunc是一个指针,因此它包含其他东西的地址;地址为8个字节。但是,为什么函数名称的大小为1个字节,因为我曾经认为函数名称是const指针,其内容是函数开始的地址。如果函数名称不是指针,那么如何将其删除?
实验后,问题仍然无法解决。
如果您刚进入C
" 指针是一个变量/em>"。
指向整数/字符等的指针与指向函数的指针之间没有区别。它的目的是指向内存中的地址,在这种情况下,该函数存储了。
另一方面,功能的名称就是函数的命名方式。正如人们在评论中建议的那样,它标识了编译器前面的功能。
如何定义函数:
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);
我还注意到您的代码中您没有使用任何&amp;。考虑以下狙击的结果:
#include <stdio.h>
void my_int_func(int x)
{
printf( "%dn", 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中的功能类型是'特殊'。像数组类型一样,您实际上无法具有函数类型的值,因此(默默地(将函数类型的表达式用于指针 - 指向函数类型的指针。
因此,每当您使用诸如my_int_func
之类的函数的名称时,它将被转换为与&my_int_func
相同的东西。为此,如果您有一个呼叫表达式,其中所谓的事物类型为函数指针类型,它将称为指向函数的指向。
这就是为什么testFunc
,*testFunc
,&testFunc
(甚至*******testFunc
之类的东西(都将它们都作为相同的值打印到printf之类的函数时。