简体   繁体   English

取消引用C ++中的void指针

[英]Dereferencing the void pointer in C++

I'm trying to implement a generic linked list. 我正在尝试实现通用链表。 The struct for the node is as follows - 节点的结构如下:

typedef struct node{
        void *data;
        node *next;      
};

Now, when I try to assign an address to the data, suppose for example for an int, like - 现在,当我尝试为数据分配地址时,以一个int为例,例如-

int n1=6;
node *temp;
temp = (node*)malloc(sizeof(node));
temp->data=&n1;

How can I get the value of n1 from the node? 如何从节点获取n1的值? If I say - 如果我说 -

cout<<(*(temp->data));

I get - 我得到-

`void*' is not a pointer-to-object type 

Doesn't void pointer get typecasted to int pointer type when I assign an address of int to it? 我将int的地址分配给它时,void指针不会被强制转换为int指针类型吗?

您必须首先将void*类型转换为指针的实际有效类型(例如int* ),以告诉编译器您希望取消引用多少内存。

A void pointer cannot be de-referenced. 无效指针不能被取消引用。 You need to cast it to a suitable non-void pointer type. 您需要将其强制转换为合适的非空指针类型。 In this case, int* 在这种情况下, int*

cout << *static_cast<int*>(temp->data);

Since this is C++ you should be using C++ casts rather than C styles casts. 由于这是C ++,因此应该使用C ++强制转换而不是C样式强制转换。 And you should not be using malloc in C++, etc. etc. 而且您不应该在C ++等中使用malloc

A void pointer cannot be dereferenced. 无效指针不能被取消引用。 You need to cast it to a suitable non-void pointer type. 您需要将其强制转换为合适的非空指针类型。 The question is about C++ so I suggest considering using templates to achieve your goal: 问题是关于C ++的,所以我建议考虑使用模板来实现您的目标:

template <typename T> struct node
{
   T *data;
   node<T> *next;      
};

then: 然后:

int n1=6;
node<int> *temp = new node<int>();
temp->data=&n1;

And finally: 最后:

cout << (*(temp->data));

Typecasting is possible, but that will be a C-style type-unsafe solution and not a C++ one. 可以进行类型转换,但这将是C风格的类型不安全的解决方案,而不是C ++。

将temp-> data类型转换为int,然后打印。

cout<<*((int *)temp->data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM