在 C 中以 void 指针的形式存储通用数据
Storing generic data in the form of void pointer in C
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;
}
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;
}