C 结构中定义的访问函数指针?
编写一个程序,使用结构2访问函数“foo”C 结构中定义的访问函数指针?,c,structure,function-pointers,C,Structure,Function Pointers,编写一个程序,使用结构2访问函数“foo” typedef struct { int *a; char (*fptr)(char*); }structure1; typedef struct { int x; structure1 *ptr; }structure2; char foo(char * c) { --- --- --- } 创建类型为structure2 将structure1类型的对象的地址分配给它(这可以通过多种方式实现) 将foo分配给上述分配
typedef struct
{
int *a;
char (*fptr)(char*);
}structure1;
typedef struct
{
int x;
structure1 *ptr;
}structure2;
char foo(char * c)
{
---
---
---
}
- 创建类型为
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;
}
structure2 *s2 = (structure2*)malloc(sizeof(structure2));
s2->ptr = (structure1*)malloc(sizeof(structure1));
s2->ptr->fptr = foo;
char x = 'a';
s2->ptr->fptr(&x);