1
I’m creating a record using struct
, where I must have a menu to insert,.
My difficulty is to create the delete function, I put a null value on the pointer of the position that will be deleted, indent all records one position, then use the realloc
to decrease a vector position. But that allocated space, which after I deleted, will be available for use of other variables?
The code is a little messy because I’m still learning dynamic allocation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct cadastro{
char nome[20];
int idade;
};
cadastro *p;
int num, num_novo, num_old, realoca=0;
char opcao,op;
void cadastra();
void exibe();
void menu();
main()
{
do{
menu();
printf("\tOpcao: "); scanf("%d",&opcao); fflush(stdin);
switch(opcao){
case 0:
break;
case 1:{
do{
cadastra();
printf("Deseja cadastrar mais (s/n): "); op=getchar(); fflush(stdin);
}while(toupper(op)!='N');
break;
}
case 2:
exibe();
break;
default:
printf("Opcao invalida.\n\n");
}
}while(opcao!=0);
getchar();
return 0;
}
void menu()
{
printf("\t[0] Sair\n\t[1] Cadastrar\n\t[2] Exibe\n\t[3] Excluir\n");
}
void cadastra()
{
if(realoca==0){
printf("Numero de cadastros: "); scanf("%d",&num); fflush(stdin);
p = (cadastro *)calloc(num, sizeof(cadastro));
int i;
for(i=0; i<num; i++){
printf("Cadastro %d\n",i+1);
printf("Nome: "); gets(p[i].nome);
printf("Idade: "); scanf("%d",&p[i].idade);fflush(stdin);
printf("\n\n");
}
realoca = 1;
}else{
num_old=num;
num=num+1;
p = (cadastro*)realloc(p,num);
int i;
for(i=num_old; i<num; i++){
printf("Cadastro %d\n",i+1);
printf("Nome: "); gets(p[i].nome);
printf("Idade: "); scanf("%d",&p[i].idade);fflush(stdin);
}
}
}
void exibe()
{
int j;
if(p==NULL)
printf("\t -- Cadastro vazio. --\n\n");
else{
for(j=0; j<num;j++){
printf("Pessoa %d\n\n");
printf("Nome: %s\n",p[j].nome);
printf("Idade: %d",p[j].idade);
puts("\n\n");
}
}
}