I\'m trying to implement a generic linked list. The struct for the node is as follows -
typedef struct node{
void *data;
node *next;
};
Typecast temp->data to int and then print.
cout<<*((int *)temp->data);
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.
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.