为什么将结构成员转换为其结构指针类型有效?

Yia*_*ael 2 c struct pointers function

我不确定用什么术语来正确解释这一点,但我已将代码单独放入一个文件中,以了解它是如何工作的,我希望有人可以进一步帮助我!

我理解的主要问题是为什么它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;
        }

        printf("Value: %d\n", test.num);
    }
}

void fcn0(test_t* test){
    printf("Entered fcn0\n");
    test->num = 0;
}

void fcn1(test_t* test){
    printf("Entered fcn1\n");
    test->num = 1;
}

void fcn2(test_t* test){
    printf("Entered fcn2\n");
    test->num = 2;
}
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 5

这行:

void (*exec)(struct test_t*)
Run Code Online (Sandbox Code Playgroud)

声明exec函数指针。该指针指向一个函数,该函数采用单个类型参数struct test_t*并且返回类型为void

当你这样做时:

test.exec = fcn1;
Run Code Online (Sandbox Code Playgroud)

该函数fcn1首先自动调整为指向该函数的指针,并将该函数指针分配给test.exec。该函数被声明为void fcn1(test_t* test);,因此指向该函数的指针与exec结构体成员具有相同的类型。

然后当你这样做时:

test.exec(&test); 
Run Code Online (Sandbox Code Playgroud)

您正在执行 指向的函数并将其作为参数test.exec传递。&test

另请注意,传递给此函数的参数没有&test具体要求。它可以是指向任何类型的结构的指针struct test_t。这只是在 C 中模拟“this”指针的一种方式,类似于 C++ 的工作方式,但需要程序员以某种方式调用函数才能工作。


Ted*_*gmo 5

void (*exec)(struct test_t*)
Run Code Online (Sandbox Code Playgroud)

这将创建exec一个指向void以 astruct test_t*作为参数的函数的指针。

...test.exec = fcn1; test.exec(&test);该函数被分配给该结构成员,并且在括号中传递函数参数以便执行该函数。但是这个设置在变量定义中是如何实际发生的呢?