取消引用C ++中的void指针 [英] Dereferencing the void pointer in C++
本文介绍了取消引用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.
这篇关于取消引用C ++中的void指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文