Dereferencing the void pointer in C++

后端 未结 4 2138
南方客
南方客 2020-12-20 06:11

I\'m trying to implement a generic linked list. The struct for the node is as follows -

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


        
相关标签:
4条回答
  • 2020-12-20 06:33

    Typecast temp->data to int and then print.

    cout<<*((int *)temp->data);
    
    0 讨论(0)
  • 2020-12-20 06:39

    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.

    0 讨论(0)
  • 2020-12-20 06:52

    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.

    0 讨论(0)
  • 2020-12-20 06:54

    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.

    0 讨论(0)
提交回复
热议问题