Chained lists - add at the end of the list

Asked

Viewed 1,403 times

3

I’m having trouble executing this code, whose goal is to add an element at the end of the list, the program is waiting for something that I don’t know what it is, then the program of the error. Some light?

I’m starting now lists, so the possibility of being a mistake beast is great hehe.

typedef struct evento_t {
double tempo;
char descricao[50];
int id_origem, id_destino;
struct evento_t *prox;
} evento_t;


bool eventos_adicionar_fim (evento_t **lista, double tempo, char descricao[], int   id_origem, int id_destino) {

evento_t *novoelemento = (evento_t*)malloc(sizeof(evento_t));
evento_t *auxiliar = *lista, *anterior = NULL;

if (novoelemento!=NULL) {
    novoelemento->tempo = tempo;
    strcpy (novoelemento->descricao, descricao);
    novoelemento->id_origem = id_origem;
    novoelemento->id_destino = id_destino;
    novoelemento->prox = NULL;

    while (auxiliar!=NULL) {
        anterior = auxiliar;
        auxiliar = auxiliar->prox;
    }

    anterior->prox = novoelemento;

    return true;
}

else {
    exit(1);
    return false;
}

}

  • 1

    Note that you did not predict the case of the list having zero elements (while will not execute and anterior will be NULL). In this situation do *lista = novoelemento;. What exactly is the error you are observing? Crash?

  • Cade the definition of the main function? Your code seems to be incomplete. post here for us to take a look: http://pastebin.com/

  • Post in the question itself, there is no reason to put in an external place.

  • As I’m running by cmd, cmd stops responding. I’ve already checked the NULL error and it still works. I think the main thing is right, because I have a function to add at the beginning and it’s working normal.

  • modified the code

  • Run in a Debugger. If your compiler is gcc, Compile with -g and perform with gdb prog.exe. give the command run and backtrace to display the error location. (From there you can also explore the value of the variables)

  • Ah, now it was. It was exactly the problem of NULL, had closed the if block in the wrong place ^^

  • Kay, if you found the solution yourself, add an answer to your own question, so we complete the cycle :)

  • I couldn’t find it myself, I had messed up the NULL deal you said

Show 4 more comments

1 answer

2


The problem is trying to insert something at the end of an empty list. In this case both the auxiliar as to the anterior are NULL. The crash will happen while doing anterior->prox = novoelemento;. Instead add a check:

if (*lista == NULL) {
    *lista = novoelemento;
} else {
    // código anterior
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.