[英]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.