Why doesn't this work?

Started by
2 comments, last by Zeraan 21 years, 8 months ago
I''m learning linked lists (no STD, just basic linked lists), and I''m attempting to add a new node at the end of list. No matter what I do, this freezes my computer! this is the code:
  
void The_Asteroids::AddAst()
{
   Tail = Tail->NewAst(Tail);
}

An_Asteroid *An_Asteroid::NewAst(An_Asteroid *curr)
{
	if(Next==NULL)
	{
		Next=new An_Asteroid;
		Next->Prev=curr;
		Next->Next=NULL;
		
		return Next;
	}

	return NULL;
}
  
The_Asteroids class is the list of An_Asteroid class. It have Head, Tail, and Current. An_Asteroid is storage for data on each asteroids, sort of like an array. When this is called, the game freezes, along with my computer. Can you explain why this is happening, and what is the correct way to do it? Thanks You know your game is in trouble when your AI says, in a calm, soothing voice, "I''m afraid I can''t let you do that, Dave"
Advertisement
I think the problem isn''t in this code. What is Next var?
Zeraan:

I don't think you can return class objects. You should probably have the NewAst function return a pointer to the next item on your linked list. Maybe something like this:


  An_Asteroid *An_Asteroid::NewAst(An_Asteroid *curr) {        if (curr->Next == NULL) {                curr->Next = new An_Asteroid;                curr->Next->Prev = curr;                curr->Next->Next = NULL;                return curr->Next;        }        else {                return NULL;        }}  

In addition, in your code, you had the function try and return both Next and NULL if curr == NULL. I'm not sure what the legal compiler response would be in that case.

John.

[edited by - JohnAD on August 19, 2002 4:43:52 PM]
Thanks, John! That did the trick, adding the curr->! Now to contiune with my game

Thanks!
Did I said thanks?


You know your game is in trouble when your AI says, in a calm, soothing voice, "I''m afraid I can''t let you do that, Dave"

This topic is closed to new replies.

Advertisement