Hi all.

I am trying to build a Binary Linked Trie but fail in basic pointer operations.Following code can be built but in debug or run mode, it breaks and outputs the error.

typedef struct node
{
	char ch;
	node *next;
};

struct node *root = NULL;

void add(struct node *leaf, char ch)
{
	leaf = new node;
	leaf->ch = ch;
	leaf->next = NULL;
}

void read()
{
	while(root->next != NULL)
		cout << root->ch;
}

int _tmain(int argc, _TCHAR* argv[])
{
	struct node *conductor;
	add(root, 'a');
	conductor->ch = 'l';
	conductor->next = NULL;
	root->next = conductor;
	
	read();
	return 0;
}

The error is "CXX0030, Expression Cannot Be Evaluated."
In step mode of debug, conductor is looks like this in Autos "{ch=???, next=???}".
It looks like a mistake about pointer arytmetichs,but I can't see it. I guess it says me "I don't know what is root->next".
By the way these are the other instructions:
Visual Studio 2010
Visual C++
Win32 Console Application
#include <iostream>
using namespace std; and not using another header file.

Thanks.

Recommended Answers

All 3 Replies

You need to allocate the memory for conductor :

int _tmain(int argc, _TCHAR* argv[])
{
	struct node *conductor = new node;   // Allocate memory
	add(root, 'a');
	conductor->ch = 'l';
	conductor->next = NULL;
	root->next = conductor;
	
	read();
	return 0;
}

You have also used a lot of C-style syntax that is not necessary in C++. You can just do

struct node
{
	char ch;
	node *next;
};

No need for the typedef , or

node *conductor = new node;

No need for the struct

Thank you for answers but in an other version i tried new and allocated memory. I done everything as you said. But the error still exist.
[TEX]CXX0030: Error: expression cannot be evaluated[/TEX]
in Autos window this error seems for conductor->next->ch and conductor->next->next;

Now I solved this problem.Thanks for help.

Solve
We need an another global node to handle NULL pointed nodes.

node * hnode;

//add function
nnode = new node;
nnode->ch = ch;
nnode->next = NULL;
leaf->next = nnode;
hnode = leaf->next;

We must keep the last node (I think). If still there is a problem in my explanations, please tell me so I can understand the solving more accurate, truely...

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.