Eliâ Melfior
Eliâ Melfior

Reputation: 369

C memory allocation, what is wrong?

(Solved) This line(in C)

(*ptr).firstNode = malloc(sizeof(node));

gives this error:

[Error] incompatible types when assigning to type 'node' from type 'void *'

So, the left part is of type "node" (which is a structure that i created), why is this not working? Does anyone know? Any help would be appreciated, will post the structs declarations if necessary.

Structs:

typedef struct node{
    int idade;
    struct node * next;
    struct node * prev;
}node;

and

typedef struct {
    node firstNode;
    node lastNode;
}dll;

Guys, the question is solved, thanks everyone that answered, would it be better to add firstNode and lastNode as pointers? or would it be better to just let them be the struct itself?

What i'm trying here is just to learn how to initialize and deal with a double linked list, this is just the creation of the list itself, next functions will be remove from the top and from the bottom, etc.

Upvotes: 2

Views: 120

Answers (2)

Rajeev Singh
Rajeev Singh

Reputation: 3332

malloc returns a void *, as the error says..

[Error] incompatible types when assigning to type 'node' from type 'void *'

you need a pointer on the left-hand side which should be of type node* in this case.

Maybe you should change the struct definition like this

typedef struct {
    node *firstNode; // pointer 
    node *lastNode;
}dll;

then (*ptr).firstNode = (node *) malloc(sizeof(node)); would work.

Upvotes: 3

afdggfh
afdggfh

Reputation: 135

Try:

typedef struct {
    node *firstNode;
    node *lastNode;
}dll;

Since the others in the comments already noted, firstNode is not a pointer, but a struct.

Upvotes: 0

Related Questions