#include "stdio.h"
int add(int x, int y)
{
return x y;
}
int withFive(int x, int (*func))
{
return (*func)(x,5);
}
int main()
{
void (*funcptr)(int) = &add;
printf("%d", withFive(10,funcptr));
return 0;
}
這段代碼似乎可以根據我對函式指標的理解進行編譯,但是有一個錯誤是函式或函式指標沒有被傳遞給withFive. 我應該如何撰寫withFive以便編譯器將引數作為函式 ptr 接受?
uj5u.com熱心網友回復:
定義應該是
int withFive(int x, int (*func)(int, int ) )
或者
int withFive(int x, int (*func)(int x, int y) )
就像在變數定義中一樣。
順便說一句: void (*funcptr)(int) = &add;應該int (*funcptr)(int,int) = &add;或者只是int (*funcptr)(int,int) = add;
uj5u.com熱心網友回復:
int withFive(int x, int (*func))
作為引數,您想要一個func回傳int 并接受兩個int作為引數的函式。
所以你需要:
int withFive(int x, int (*func)(int, int))
然后:
{
return (*func)(x,5);
}
您不需要取消參考func. 寫吧
return func(x, 5);
然后:
void (*funcptr)(int) = &add;
那又是錯誤的型別。而且您不需要獲取 的地址add。寫吧:
int (*funcptr)(int, int) = add;
或者你可以寫:
printf("%d", withFive(10,add));
uj5u.com熱心網友回復:
在你的情況下,它必須是int withFive(int x, int (*func)(int,int)). 但是,使用 C 的原始函式指標語法是非常不可讀的。推薦的做法是始終使用 typedef,如下所示:
typedef int operation_t (int x, int y); // function type acting as "template"
int add (int x, int y);
int withFive(int x, operation_t* op); // op is a pointer to function
...
withFive(10, add);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464560.html
