c - 在 C 中以 void 指针的形式存储通用数据

标签 c pointers void-pointers

I am trying to use void pointer to store generic data in C language

这是存储通用数据类型的结构

 struct Node{
        int id;  // Id of the node 
        void *data; // Variable Which stores data
    };

我是通过这种方式存储数据的

int graph_setnode_data(graph_t *graph,int id,void *data){
    struct Node *node = getnode(graph,id);
    if(node != NULL){
        node->data = data;
        return 0;
    }
    return 1;
}

并通过

访问数据
void* graph_getnode_data(graph_t *graph,int id){
    struct Node *node = getnode(graph,id);
    if(node != NULL){
        return node;
    }
    return NULL;
}

下面是我如何使用这些方法

struct Person{
    char *name;
    int age;
};
int main(){
    struct Person *person = malloc(sizeof(struct Person));
    person->name = "Goutam";
    person->age = 21;

    graph_t *graph = graph_init(2);
    graph_createpath(graph,0,1);
    graph_createpath(graph,1,0);
    graph_setnode_data(graph,0,(void *)person);
    struct Person *data =(struct Person *) graph_getnode_data(graph,0);
    printf("%d\n",data->age);
    graph_destroy(graph);
    return 0;
}

但是我得到了输出:

38162448

最佳答案

您返回的是节点,而不是节点中存储的数据:

void* graph_getnode_data(graph_t *graph,int id){
    struct Node *node = getnode(graph,id);
    if(node != NULL){
        return node->data; // <---- This should fix the bug.
    }
    return NULL;
}

关于c - 在 C 中以 void 指针的形式存储通用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30443979/

相关文章:

C 结构到 void* 指针

c - 如何处理 open() 返回 1

c - 跳转到stm32f4上的第二个固件

android - C 源代码不会为 ARM 架构编译

c++ - 为具有指针成员的类正确重载赋值运算符

c++ - 什么是 `R(*pf)(void*, Args...)` ,指向方法的函数指针?

c - 如何使用英特尔内部函数从 8 位整数数组构建 32 位整数?

创建节点线性链表

c++ - 什么是指向 x 个整数数组的指针?

c++ - 是否将两个 void 指针与 C++ 中定义的不同对象进行比较?