如何在 C 中取消引用和调用结构的函数



假设我们有这个结构:

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)但这也会导致段错误

我打电话给酒吧

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

这是一个演示程序

#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 = %in", 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 = %in", i );
}
int main(void) 
{
struct foo *f = malloc( sizeof( struct foo ) );
f->func = atoi;
bar( f );
free( f );
return 0;
}

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

#include "stdio.h"
typedef struct _ms
{
int (*hello)(int);
int (*bye)(int);
struct _ms *ms;
}mystruct_t;
int h(int x) 
{
return printf("Hello %dn", x);
}
int g(int x) 
{
return printf("Bye %dn", 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 charsn", 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