I have a binary tree program that is trying to retrieve a name. I've already inserted names into the tree correctly and can see this at output. Now I'm trying to check for a name in the tree and calling that input "key". My program wants to take that key and compate it with data found from the function getName(). My program crashes at getName() in the strcpy line: Here is my code for the recursive retrieve:

bool BST::recurRetrieve(const char *key,data& aData,int index)const
{
	if(items[index].empty)
	{
		return false;
	}
	items[index].data.getName(temp);    //char *temp
	
    if (strcmp(temp,key)== 0)
	{
		aData = items[index].data;
		return true;
    }
	else
	{
		if(aData < items[index].data)
			recurRetrieve(key,aData,2*index+1);
		else
			recurRetrieve(key,aData,2*index+2);
	}
}

This is my code for getName():

void data::getName (char * name)const
{
    /*name = new char[strlen(name)+1];*/
	strcpy(name, this->name);       //program crashes right after this step
}

I'm really hoping this is a matter of syntax, (in which case I'm a goof), instead of my algorithm being really wrong. Thanks for looking. I'm going insane :S

Recommended Answers

All 3 Replies

Well it looks for all the world like your temp isn't pointing anywhere.
A crude fix might be to make temp an array of char, rather than just a pointer to char.

Better, use std::string for all your strings.

Good call. I created an array: char temp[MAX_SIZE].

My error now, is C2664: 'data::getName' : cannot convert parameter 1 from 'const char [256]' to 'char *'

getName header:

void getName(char * name)const;

.cpp

void data::getName (char * name)const
{
    
	strcpy(name, this->name);       
}

How getName is called from recurRetrieve:

items[index].data.getName(temp);  //this is where the error goes to

I've tried within the call: (*temp) and (&temp). I've checked to make sure parameters are in their proper order when defined and declared. I don't know what else it can be.

I left getName as it was and rewrote my recurRetrieve function. Now I'm not calling getName and everything works.

bool BST::recurRetrieve(const char *key,data& aData,int index)const
{
	char temp[MAX_NAME_SIZE];
	strcpy(temp,key);
	data tmpData(temp);

	if(items[index].empty)
	{
		return false;
	}
    
	
	//items[index].data.getName(tmp);    
	
    //if (strcmp(tmp,key)== 0)
    if (tmpData==items[index].data)
	{
		aData = items[index].data;
		return true;
    }
	else
	{
		if(tmpData < items[index].data)
			recurRetrieve(key,aData,2*index+1);
		else
			recurRetrieve(key,aData,2*index+2);
	}
}
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.