Problems with CRUD in C (delete method)
In the Delete function, the user will inform an RA that wants to delete, when the RA exists in the memory it deletes, this part of the code works... The problem is when he does not find in the memory the RA... The system crashes
void deletar(void){
system("cls");
//RA que o usuario quer deletar
int n;
printf("Digite o RA que deseja deletar: ");
scanf("%i", &n);
do{
//Esta parte esta ok
if(p->ra == n){
//deleta a struct da memoria
free(p);
printf("\n\n\nAluno deletado com sucesso\n");
system("pause");
system("cls");
//limpando a tela e voltando para o menu principal
main();
}
//Quando ele nao acha o RA o programa trava.
//unica coisa que falta pra finalizar o metodo
if (p->anterior==NULL){
printf("\n\n\nERRO 404: RA nao existe no sistema\n");
system("pause");
system("cls");
//limpando a tela e voltando para o menu principal
main();
}
//vai pra proxima struct
p = p->anterior;
}while(1);
}
I put a condition for if the previous one is NULL it means that it has already traversed all structs, then it does not exist, but it is not working
2 answers
The error is in the return of the "Delete" function, where is "main()" (which makes no sense, as it would be a recursive call of the main program) should be "return".
void deletar(void)
{
system("cls");
//RA que o usuario quer deletar
int n;
printf("Digite o RA que deseja deletar: ");
scanf("%i", &n);
do {
//Esta parte esta ok
if (p->ra == n) {
//deleta a struct da memoria
free(p);
printf("\n\n\nAluno deletado com sucesso\n");
system("pause");
system("cls");
//limpando a tela e voltando para o menu principal
// main(); // <------------------------- ERROR!!!
return;
}
//Quando ele nao acha o RA o programa trava.
//unica coisa que falta pra finalizar o metodo
if (p->anterior==NULL){
printf("\n\n\nERRO 404: RA nao existe no sistema\n");
system("pause");
system("cls");
//limpando a tela e voltando para o menu principal
// main(); // <--------------- ERRO!!!
return;
}
//vai pra proxima struct
p = p->anterior;
} while (1);
}
Instead of the Delete function calling the main every time after its execution, I followed the advice of @zentrunix and looped the main function, so when the Delete function ends, it automatically returns to main.
void deletar(void){
system("cls");
//RA que o usuario quer deletar
int n=0;
printf("Digite o RA que deseja deletar: ");
scanf("%i", &n);
while(p->anterior!=NULL){
if(p->ra == n){
//deleta a struct da memoria
free(p);
printf("\n\n\nAluno deletado com sucesso\n");
system("pause");
system("cls");
//limpando a tela e voltando para o menu principal
main();
}
p = p->anterior;
}
//Se nao entrar no if significa que nao foi encontrado o RA
printf("\n\n\nERRO 404: RA nao existe no sistema\n");
system("pause");
//limpando a tela e voltando para o menu principal
system("cls");
}