Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 结构中定义的访问函数指针?_C_Structure_Function Pointers - Fatal编程技术网

C 结构中定义的访问函数指针?

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分配给上述分配

编写一个程序,使用结构2访问函数“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);