简体   繁体   中英

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 n1=6;
node *temp;
temp = (node*)malloc(sizeof(node));
temp->data=&n1;

How can I get the value of n1 from the node? 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?

您必须首先将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*

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

Since this is C++ you should be using C++ casts rather than C styles casts. And you should not be using malloc in C++, etc. etc.

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:

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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