gpt4 book ai didi

C结构问题

转载 作者:太空狗 更新时间:2023-10-29 15:14:22 25 4
gpt4 key购买 nike

我有一个这样记录的接口(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com