代码之家  ›  专栏  ›  技术社区  ›  wrapperm

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

  •  0
  • wrapperm  · 技术社区  · 16 年前

    使用结构结构2编写访问函数“foo”的程序。

    typedef struct
    {
       int *a;
       char (*fptr)(char*);
    }structure1;
    
    typedef struct
    {
       int x;
       structure1 *ptr;
    }structure2;
    
    char foo(char * c)
    {
    ---
    ---
    ---
    }
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Amarghosh    16 年前
    structure2 *s2 = (structure2*)malloc(sizeof(structure2));
    s2->ptr = (structure1*)malloc(sizeof(structure1));
    s2->ptr->fptr = foo;
    char x = 'a';
    s2->ptr->fptr(&x);
    
        2
  •  0
  •   dirkgently    16 年前
    • 创建类型的对象 structure2
    • 为其分配类型的对象的地址 structure1 (这可以用很多方法实现)
    • 分配 foo 分配给上述人员 结构1 对象的 fptr 成员
    • 呼叫 使用:

      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;
    }
    
    推荐文章