我不确定用什么术语来正确解释这一点,但我已将代码单独放入一个文件中,以了解它是如何工作的,我希望有人可以进一步帮助我!
我理解的主要问题是为什么它void (*exec)(struct test_t*);确实有效?结构成员将自身转换为结构指针?这让我很困惑。
另外,在 switch-case 语句中,我理解在这些行中test.exec = fcn1; test.exec(&test);函数被分配给该结构成员,并且在括号中传递函数参数以便执行该函数。但是这个设置在变量定义中是如何实际发生的呢?
我基本上是分配一个函数作为结构成员吗?如果是,那么在编译结构之前它如何了解自身?这个语法是(*x)(struct y*)用来做什么的?
typedef struct test_t{
int num;
void (*exec)(struct test_t*);
}test_t;
void fcn0(test_t* test);
void fcn1(test_t* test);
void fcn2(test_t* test);
int main(){
while(1){
test_t test = {
.num = 0,
.exec = fcn0
};
printf("Enter a number: ");
scanf("%d", &test.num);
switch (test.num)
{
case 1:
test.exec = fcn1;
test.exec(&test);
break;
case 2:
test.exec = fcn2;
test.exec(&test);
break;
default:
test.exec = fcn0;
test.exec(&test);
break;
} …Run Code Online (Sandbox Code Playgroud)