//sorry i am trying to create a list using a pointer to the next struct
//PROBLEMS:
//with dev-cpp:
//1. when i try to print the list the output has no sense
//2. if i use the malloc to allocate memory for the struct film it crashes
returning an high number
//il = (film*) malloc(sizeof(film));//that's what i had written with malloc notation...
//of course i had included the <cstdlib>
//with code-blocks
//1. when i try to print the list there's a third element of the list that shouldn't be there...maybe it's a problem with the print function -__-
Learn classes, then approach this topic again. Your code is really bad, because you'll get massive memory leaks - you don't have any convenient way to delete memory you've assigned, and you don't do that. Classes have constructors and destructors helping you with manual memory management.
Anyway, the bug lies on line 33 and 34. Read about assigning pointers. You probably think you're copying value of pt1 to pt2, but you don't do that.
I didn't do it with classes because i didn't want to do it with classes, and i didn't free nothing because it wasn't necessary... and i don't know what you mean with memory leaks with such a little program... i know classes have constructors and what?
ah? are you serious? read about assigning pointers? yes, cause couldn't I a assign a pointer to another pointer that are pointing to variables of the same type?lol, yes, i am copying the address of structer, which is pointing to the first element of struct, to il, and i can do it! if not, tell me a reason
Your code all looks fine. I think that line 65 is the reason for the extra item. Just comment it out. Your insertInTheHead function takes care of all allocations.
You do have a memory leak in that the new-ed films are never deleted, but that shouldn't cause the program to not work right.
EDIT: A function for deleting a film lists nodes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void destroyList(film*& il)// post condition: il = NULL
{
int N = 0;// film counter (a frill)
while(il != NULL)
{
film* temp = il;
il = il->next;
delete temp;
++N;
}
cout << "deleted " << N << " films from list." << endl;
}
Yes, it works, but shouldn't we first allocate memory to the pointer il (of type film) in the main source?
//and if I use malloc to allocate the pointer il the program crashes, why?
il = (film*)malloc( sizeof(film));
//with this notation i am just allocatin memory for a struct
//shouldn't be there any problems, but I can't understand the reason of my crash...
Thank you to y'all! It s of course of the line 65, because I am allocating memory to another struct and when I try to create my "new" list (from zero), calling the insertInTheHead function, there is already an existing node, that I have just created with (il=new film;). And because I am creating my list inserting nodes in the head, when I print it, the first node I created (with "il = new film;") is printed after the second, because it becomes the last node of the list!! :)