malloc

I'm having trouble with malloc. I copied this from a tutorial and tried to run it but it didn't work. It is supposed to insert a new element in a linked list (when I call it from main).


llist ajouterEntete(llist liste, int valeur)
element* nouvelElement = malloc(sizeof(element));
nouvelElement->val = valeur;
nouvelElement->nxt = liste;
return nouvelElement;
}
I get this error message:

list.C: In function `element* ajouterEntete(element*, int)':
list.C:25: error: invalid conversion from `void*' to `element*'


I then tried to change the line to:
element * nouvelElement = (element *) malloc(sizeof(element));

I don't get any error messages but it doesn't work.

try this
 
nouvelElement = liste;

Last edited on
Use new. It's more c++ than malloc (a carry-over from C) and I can tell you how that works.
Dionisis - I see that i'm missing { before the second line of my code.

You want me to add this line or replace another with it? Sorry for the stupid question.


Yes I tried new, this is what I tried:

element * nouvelElement;
nouvelElement = new element;

Does this make sens? probably not cause it doesn't work.
I'm pretty sure that's correct but you may want to check this first, because my DMA is a little rusty:
http://www.cplusplus.com/doc/tutorial/dynamic/
sorry my fault!
i want you to add it after: nouvelElement->nxt = liste;
you add a new node to the head of the list don't you i mean that's what that piece of code does
isn't it?
Also i want to ask what happens with the return value nouvelElement
what does the program you returned it do with it?
Thank you both for the replies

Dionisis, I tried it and it still doesn't work. For now, my program just wants to add 10 elements and read them.

tummychow - thanks, I will read up on new and try to use it instead of malloc. I will eventually get it, i'm sure!
closed account (S6k9GNh0)
malloc returns a void pointer. A void pointer is not valid with a type pointer unless it is casted.

Try this:

element* nouvelElement = (element*)malloc(sizeof(element));

This code that you are using seems to be using a non-standard C-based linked list created by the maker of the tutorial. Because of this, I'm positive that you are using a C compiler instead of a C++ compiler which doesn't allow for the use of new (without the proper explicit linking and declarations). C++ is heavily based on C but I want to make sure that you understand that they are definitely two different languages.
Last edited on
Thank you everyone. I'm using a C++ compiler. Not sure why the malloc was not working (I mean not sure what I was doing wrong!!!), but I figured it out with new.
Topic archived. No new replies allowed.