C结构问题

标签 c struct

我有一个这样记录的接口(interface):

typedef struct Tree {
  int a;
  void* (*Something)(struct Tree* pTree, int size);
};

然后据我所知,我需要创建它的实例,并使用 Something 方法来放置“大小”的值。 所以我愿意

struct Tree *iTree = malloc(sizeof(struct Tree));
iTree->Something(iTree, 128);

但是总是初始化失败。我这样做对吗? 为什么 Something 方法的第一个成员是指向同一个结构的指针?

谁能解释一下?

谢谢

最佳答案

您必须将 Something 设置为 something 因为它只是一个函数指针而不是函数。您使用 malloc 创建的结构仅包含垃圾,并且在使用之前需要设置结构字段。

struct Tree *iTree = malloc(sizeof(struct Tree));
iTree->a = 10; //<-- Not necessary to work but you should set the values.
iTree->Something = SomeFunctionMatchingSomethingSignature;
iTree->Something(iTree, 128);

更新

#include <stdlib.h>
#include <stdio.h>

struct Tree {
    int a;
    //This is a function pointer
    void* (*Something)(struct Tree* pTree, int size);
};

//This is a function that matches Something signature
void * doSomething(struct Tree *pTree, int size)
{
    printf("Doing Something: %d\n", size);
    return NULL;
}

void someMethod()
{
    //Code to create a Tree
    struct Tree *iTree = malloc(sizeof(struct Tree));
    iTree->Something = doSomething;
    iTree->Something(iTree, 128);
    free(iTree);
}

关于C结构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6583261/

相关文章:

C 释放动态分配的结构数组

从结构调用函数(C/汇编)

初始化指针 slice 中的 Golang 匿名结构

c - C 结构编程

swift - 通过函数传递时不能修改对象数组?

c - 程序从字符串中删除特殊字符和数字并仅打印英文字母

共享内存中的 C 结构成员指针 (mmap)

c - 12 :4: error: variable-sized object may not be initialized

c - 不断提示用户直到提供有效值 - while 循环 C 编程

c# - 为什么.NET 的 Version 是类而不是结构?