I am trying to delete structure entries and then use realloc
to free the memory. My structure is
typedef struct person {
char fname[20];
char lname[20];
int number[10];
}person;
Im using a function to delete inputted entries
void delInfo(int*,person*);
The way the delete function is supposed to work is by locating said entry, shift back all records after that, then freeing last record with realloc
.
The code for it so far looks like this
void delInfo(int *num_entries,person*contacts){
char delfirst[20];
char dellast[20];
printf("\n First Name: ");
scanf("%s",delfirst);
printf(" Last Name: ");
scanf("%s",dellast);
int i=0;
for (i=0; i<*num_entries;i++){
if (delfirst==contacts[i].fname && dellast==contacts[i].lname){
}
}
}
So far I can search for a match with the first and last name, but dont know what happens if I move every entry "down one." If matching entry is contacts[i] something like
int c;
for (c=i+1;c<*num_entries;c++){
contacts[i].fname=contacts[c].fname;
contacts[i].lname=contacts[c].lname;
contacts[i].number=contacts[c].number;
}
contacts=(person*)realloc(contacts,sizeof(contacts)*(num_entries-1));
If I do that to all entries AFTER the one I plan on deleting, do they just "overwrite" the entry I want to delete, then I can realloc
to shorten the structure array and essentially free the memory?
If i
is the index of the entry that you want to delete, all you really need to do is:
for (c = i; c < *num_entries - 1; c++)
contacts[c] = contacts[c+1];
Then you can reallocate for the smaller dynamic array. Structs can be assigned to compatible structs, so you don't need to assign the fields of the structs individually.