【问题标题】:How to dereference and call a function of a struct in C如何在 C 中取消引用和调用结构的函数
【发布时间】:2019-12-02 21:56:45
【问题描述】:

假设我们有这个结构:

typedef struct foo {
   int (*func)(char *param);
} foo;

我们有这个原型:

void bar(foo *f){
  char *t = something
  int a = f->func(t)
  do stuff with a
}

但这在初始化 int a 时会出现段错误。我也试过int a = f->func(t),但这也会导致段错误

我叫bar by

foo *baz = malloc(sizeof(foo));
baz->func = &somefunction;
bar((foo *) &baz);

【问题讨论】:

  • 在使用struct 成员之前,您必须像其他成员一样初始化它。
  • foo baz = initializing it。有你的问题。但更严重的是,向我们展示实际代码,因为我们无法指出我们看不到的代码中的问题。请看How to create a Minimal, Reproducible Example
  • 我确实初始化了它。我编辑了我的帖子
  • 请显示实际代码,即显示问题的Minimal Reproducible Examplevoid bar(foo *f); 不会编译。
  • 现在你只是在编随机码。 foo 不是函数指针类型。第四次 - 向我们展示实际代码作为最小可重现示例 - 也就是说,构建一个简单的完整示例,我们可以自己复制并运行以查看问题。

标签: c pointers dereference


【解决方案1】:

这是一个演示程序

#include <stdio.h>
#include <stdlib.h>

struct foo {
     int (*func)( const char *param );
};


void bar( struct foo *f)
{
    int i = f->func( "123" );

    printf( "i = %i\n", i );
}

int main(void) 
{
    struct foo f = { atoi };

    bar( &f );

    return 0;
}

程序输出是

123

或者

#include <stdio.h>
#include <stdlib.h>

struct foo {
     int (*func)( const char *param );
};


void bar( struct foo *f)
{
    int i = f->func( "123" );

    printf( "i = %i\n", i );
}

int main(void) 
{
    struct foo *f = malloc( sizeof( struct foo ) );
    f->func = atoi;

    bar( f );

    free( f );

    return 0;
}

【讨论】:

    【解决方案2】:

    这与访问结构的任何其他成员完全相同

    #include "stdio.h"
    
    typedef struct _ms
    {
        int (*hello)(int);
        int (*bye)(int);
        struct _ms *ms;
    }mystruct_t;
    
    int h(int x) 
    {
        return printf("Hello %d\n", x);
    }
    
    int g(int x) 
    {
        return printf("Bye %d\n", x);
    }
    
    void call(mystruct_t *str)
    { 
        int charsprinted;
        charsprinted = str -> hello(10);
        charsprinted += str -> bye(20);
    
        charsprinted = str -> ms -> hello(50);
        charsprinted += str -> ms -> bye(50);
    
    
        printf("Call: printd %d chars\n", charsprinted);
    }
    
    int main()
    {
        mystruct_t str1 = {.hello = h, .bye = g};
        mystruct_t str = {.hello = h, .bye = g, .ms = &str1};
    
        call(&str);
    
        str.hello(100);
        str.bye(1000);
        str.ms -> hello(2000);
        str.ms -> bye(2000);
    }
    

    https://godbolt.org/z/hBFpGC

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多