出于好奇,我想了解指向函数的指针在 C 中是如何工作的。
为了将函数关联到 typedef,我在其中声明了一个指针,然后我在其中存储了所需函数的地址。
这是我能够实现的:
typedef struct
{
void (*get)(char*, int);
char string[10];
} password;
int main()
{
password userPassword;
userPassword.get = &hiddenStringInput;
userPassword.get(userPassword.string, 10);
return EXIT_SUCCESS;
}
虽然这确实完美地工作,但我希望“userPassword.get”成为一个快捷方式,在使用时调用 hiddenStringInput 函数并填写请求的参数(在本例中,一个字符数组和一个整数) .
基本上,因为我总是将 userPassword.get 与参数“userPassword.string”和“10”结合使用,所以我试图找出一种方法以某种方式将这些参数存储在指向的指针中到 hiddenString 函数。有可能吗?
最佳答案
我认为这通常是通过提供"dispatch"功能来实现的:
void get(password * pw) {
pw->get(pw->string, 10);
}
然后,在将 userPassword.get
设置为您的函数后,您只需调用:
get(userPassword);
显然,当为多个函数完成时,这会添加一些样板代码。不过,允许实现更有趣的“类似类”的东西。
关于c - 是否可以将函数参数存储在函数指针中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55983219/