Hi,

I'm currently trying to create a linked list to use with a BSP Tree, however the root node keeps on losing its' values as soon as I leave the function. The code is quite extensive, so I'll try to post the relevant sections. This is the header file.

OpenGLView.h

struct NODE {
	int id;
	NODE *front;
	NODE *behind;
	NODE *next;
};

...

class COpenGLView : public CView
{
protected:
...
	NODE*			CreateNode(NODE *parent, int id);
	void			GenerateNodeList(NODE *root);
	void			DeleteNodeList(NODE *node);

	NODE *root; // root node pointer
}

Then in one of the CPP files, I have:

// Creates a linked list for the purpose of the BSP tree
void COpenGLView::GenerateNodeList(NODE *root)
{
	NODE *node = NULL;
	root = NULL;

	for(int i = 0; i < world.size(); i++) {
		if(root == NULL) {
			root = CreateNode(root, world[i].id);
			node = root;
		} else 
			node = CreateNode(node, world[i].id);
	}
}

NODE * COpenGLView::CreateNode(NODE *parent, int id)
{
	NODE *node = new NODE;
	node->id = id;
	node->behind = NULL;
	node->front = NULL;
	node->next = NULL;
	
	if(parent != NULL)
		parent->next = node;

	return node;
}

void COpenGLView::DeleteNodeList(NODE *node)
{
	if(node->next != NULL)
		DeleteNodeList(node->next);

	delete node;
}

Within the GenerateNodeList function, it works fine; values are assigned correctly and retained, however as soon as I leave the function the variable root loses all of its' values and I of course run into access violation errors.

Is there something simple (or not-so-simple) I'm missing? Because I was under the assumption that because the root node is declared in the header file as a 'global variable', it would retain its' data even after leaving the function.

Any help would be greatly appreciated.
Thanks.

Recommended Answers

All 2 Replies

Member Avatar for jencas
NODE *node = NULL;

You don't have a global pointer!!!!!! node is a variable in the scope of GenerateNodeList(). The lifetime of node ends with leaving the scope of GenerateNodeList().

You don't have a global pointer!!!!!! node is a variable in the scope of GenerateNodeList(). The lifetime of node ends with leaving the scope of GenerateNodeList().

Potentially you need to read both the code correctly and the question. Both refer to a globally declared Node pointer named root.

-----------------------------------------

@OP

The problem you have is name ambiguity.

The method signature is:

void COpenGLView::GenerateNodeList(NODE *root)

Therefore when referring to 'root' within this function it is referring to the 'root' in the function definition and not the 'root' defined as a global variable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.