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

问题描述 投票:0回答:2

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

我理解的主要问题是为什么

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;
}```
c function pointers struct
2个回答
1
投票

这一行:

void (*exec)(struct test_t*)

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

当你这样做时:

test.exec = fcn1;

函数

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

然后当你这样做时:

test.exec(&test); 

您正在执行

test.exec
指向的函数并将其
&test
作为参数传递。


1
投票
void (*exec)(struct test_t*)

这使得

exec
成为指向
void
函数的指针,该函数采用
struct test_t*
作为参数。

...

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

  • test.exec
    被指定为指向
    fcn1
  • 然后使用
    &test
    作为参数来调用所指出的函数。与直接调用该函数效果相同:
    fcn1(&test);
    
© www.soinside.com 2019 - 2024. All rights reserved.