下面的代码按照广告的方式工作。但是,我不太了解此应用程序中“typdef”的机制(我了解它对结构的用途),因此我想删除它们以进行代码比较。我可以毫无问题地删除 struct typedef,但对指针 typedef 的理解不够好,无法用其他代码替换它。我希望得到一些帮助:-)
当我将“正常”int *ptr 分配给结构时,程序不再工作。看来我的问题是将 struct ptr 定义为函数模板。
typedef int ( *ptrToFunc ) ( int a, int b ); // 与 WHAT 相同?
/****************************************************************
* Call function using pointer saved to struct *
* *
* The result: *
* Add: 8 *
* Mult: 15 *
****************************************************************/
#include "allheaders.h" // for me
// #include <stdio.h> // everybody else
typedef int ( *ptrToFunc ) ( int a, int b ); // create func ptr var
typedef struct data { // struct template
int result; // to store result
ptrToFunc pFunc; // function pointer
} stData;
int Add ( int a, int b ) { // Add two num a and b
return a + b;
}
int Multi ( int a, int b ) { // Multiple two num a and b
return a * b;
}
int main ( int argc, char *argv[] ) {
stData stRecord;
// put desired ptr to func in struct then call function
stRecord.pFunc = Add; // func ptr var pts to Add funct
stRecord.result = stRecord.pFunc ( 5, 3 ); // save answer in struct
printf ( " Add: %d\n", stRecord.result );
stRecord.pFunc = Multi; // func ptr var pts to Multi funct
stRecord.result = stRecord.pFunc ( 5, 3 ); // save answer in struct
printf ( " Mult: %d\n", stRecord.result );
return 0;
}
我找到了一个足够接近解决问题的示例here。它就像直接替换 def 一样简单(我一直在尝试为结构中的普通指针赋值)。
这就是我需要做的...
#include "allheaders.h" // for me
// #include <stdio.h> // everybody else
typedef struct data { // struct template
int result; // to store result
int ( *pFunc ) ( int a, int b ); // create function pointer
} stData;