在 C++ 中取消引用 void 指针
我正在尝试实现一个通用链表.该节点的结构如下 -
I'm trying to implement a generic linked list. The struct for the node is as follows -
typedef struct node{
void *data;
node *next;
};
现在,当我尝试为数据分配地址时,假设例如 int,例如 -
Now, when I try to assign an address to the data, suppose for example for an int, like -
int n1=6;
node *temp;
temp = (node*)malloc(sizeof(node));
temp->data=&n1;
如何从节点获取 n1 的值?如果我说 -
How can I get the value of n1 from the node? If I say -
cout<<(*(temp->data));
我明白了 -
`void*' is not a pointer-to-object type
当我为它分配一个 int 地址时,void 指针不会被类型转换为 int 指针类型吗?
Doesn't void pointer get typecasted to int pointer type when I assign an address of int to it?
推荐答案
您必须首先将 void*
类型转换为实际有效的指针类型(例如 int*
)到告诉编译器您希望取消引用多少内存.
You must first typecast the void*
to actual valid type of pointer (e.g int*
) to tell the compiler how much memory you are expecting to dereference.
相关文章