Im trying to implement a doubly linked list where the nodes are stored on the stack but the data of the nodes on the heap. You can add a new node with data to the list with push() and remove the last element with pop().
I have problems with the push() method.
#include <iostream>
using namespace std;
struct Data {
string name;
int age;
};
struct Node {
struct Node *next;
struct Node *previous;
struct Data *d;
};
struct Node *first;
struct Node *last;
void init() {
first = last = NULL;
}
void push(Data d) {
Node *temp;
if(first == NULL){
first = new Node();
first->d = malloc(sizeof(struct Data *));
first->next = NULL;
first->previous = NULL;
last = first;
} else if(last->next == NULL) {
last->next = new Node();
temp = last;
last = last->next;
last->previous = temp;
last->d = first->d = malloc(sizeof(struct Data *));
}
}
int main(int argc, char *argv[]) {
init();
Data d;
d.name = "Name1";
d.age = 19;
push(d);
d.name = "Name2";
d.age = 24;
push(d);
d.name = "Name3";
d.age = 25;
push(d);
d.name = "Name4";
d.age = 18;
push(d);
d.name = "Name6";
d.age = 20;
push(d);
}
I get always the following Error:
Untitled.cpp:29:12: error: assigning to 'struct Data *' from incompatible type 'void *'
first->d = malloc(sizeof(struct Data *));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Untitled.cpp:38:22: error: assigning to 'struct Data *' from incompatible type 'void *'
last->d = first->d = malloc(sizeof(struct Data *));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 errors generated.
Why do I get the following error? How to fix it? What Im doing wrong?