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;
}
}
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?– Guilherme Bernal
Cade the definition of the main function? Your code seems to be incomplete. post here for us to take a look: http://pastebin.com/
– gvsrepins
Post in the question itself, there is no reason to put in an external place.
– Guilherme Bernal
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.
– Kay
modified the code
– Kay
Run in a Debugger. If your compiler is gcc, Compile with
-g
and perform withgdb prog.exe
. give the commandrun
andbacktrace
to display the error location. (From there you can also explore the value of the variables)– Guilherme Bernal
Ah, now it was. It was exactly the problem of NULL, had closed the if block in the wrong place ^^
– Kay
Kay, if you found the solution yourself, add an answer to your own question, so we complete the cycle :)
– Guilherme Bernal
I couldn’t find it myself, I had messed up the NULL deal you said
– Kay