使用结构结构2编写程序以访问函数“foo”。
typedef struct
{
int *a;
char (*fptr)(char*);
}structure1;
typedef struct
{
int x;
structure1 *ptr;
}structure2;
char foo(char * c)
{
---
---
---
}
答案 0 :(得分:1)
structure2 *s2 = (structure2*)malloc(sizeof(structure2));
s2->ptr = (structure1*)malloc(sizeof(structure1));
s2->ptr->fptr = foo;
char x = 'a';
s2->ptr->fptr(&x);
答案 1 :(得分:0)
structure2
structure1
类型对象的地址(这可以通过多种方式完成)foo
分配给上面分配的structure1
对象的fptr
成员使用以下方式致电foo
structure2 s2;
// allocate
char c = 42;
s2.ptr->fptr(&c); // if this
示例:
typedef struct
{
int *a;
char (*fptr)(char*);
}structure1;
typedef struct
{
int x;
structure1 *ptr;
}structure2;
char foo(char * c)
{
return 'c';
}
int main()
{
structure1 s1;
structure2 s2;
s1.fptr = foo;
s2.ptr = &s1;
char c = 'c';
printf("%c\n", s2.ptr->fptr(&c));
return 0;
}