I'm getting a runtime error, and I can't figure out why.
I'm developing the insert method of a btree. Below is the code of insert()

void insertar(btree* r, int dato){
    int pos=0;
    btree* encontrado= buscar(&*r, dato, 0);  //buscar() searches if dato already exists
    if (encontrado==NULL)
        printf(" data already exists");
    else
    if (encontrado!=NULL){ //ERROR! why??
    pos=buscar_nodo(&(*r), dato); //tells me in which position I have to insert the new data
    }
}

buscar() returns NULL if the data already exists, else returns pointer of the leaf.
I know the error appears when encontrado!=NULL, but why?
Is there other way to evaluate if a pointer of structure is NULL?
help please! :'(

Recommended Answers

All 2 Replies

>> Is there other way to evaluate if a pointer of structure is NULL?

if (encontrado==NULL)

You already do it here. Not sure I understand the question.


>> buscar() returns NULL if the data already exists, else returns pointer of the leaf.

If the data already exists in what? In the tree? This is a binary search tree? You're trying to insert a new element? Without seeing the other functions it's a bit hard to speculate. Also you say you have an error, but what is it?

This line seems odd.

pos=buscar_nodo(&(*r), dato);

Why would you dereference something, then take the address? Isn't that the same as

pos=buscar_nodo(r, dato);

Anyway, you might need to show some more code, tell us more about the error, and maybe provide an interpretation. I fail to see the point of the call to buscar_nodo. I thought you already found the insert position and it's encontrado? But you don't do anything with it. You're passing the top of the tree to another function. In short, the code looks off, but I'm at a loss at how to fix it since I can't see the rest of it.

Also, this is a little redundant:

if (encontrado==NULL)
    printf(" data already exists");
else
    if (encontrado!=NULL){
        pos=buscar_nodo(&(*r), dato);
    }

As Vernon points out, you've already tested encontrado , so there's no need to do it again:

if (encontrado==NULL)
{
    printf(" data already exists");
}
else
{
    pos=buscar_nodo(&(*r), dato);
}
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.