Dereferencing the void pointer in C++

痴心易碎 提交于 2019-12-18 09:26:36

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


Typecast temp->data to int and then print.

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


来源:https://stackoverflow.com/questions/10615018/dereferencing-the-void-pointer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!