I am really struggling with understanding what is actually going on when using malloc
and realloc
while using structures in C. I am trying to solve the phonebook problem where I have to create a phonebook that can add, delete, and show entries. There can be an unlimited number of entries so I have to define my structure array dynamically. My delete feature also has to find the desired entry, shift back all entries after that, then use realloc
to free last entry. This is where a basic understanding of realloc
would really help me I think.
The only part I think I have working properly is the add feature and I still don't know if I set that up properly - I just know it is working when I run it. If someone on a very basic level can help me I would appreciate it.
Here is my mess of code :-(
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getEntry(int *);
typedef struct person {
char fname[20];
char lname[20];
int number[10];
}person;
void getInfo(int *,int,person*);
void delInfo(int*,int,person*);
void showInfo(int*,int,person*);
int main(){
int a=0;
int i=0;
int con=0;
person* contacts=(person*)malloc(sizeof(person));
person* pcontacts;
pcontacts=(person*)calloc(0,sizeof(person));
getEntry(&a);
while (a!=4){
switch (a){
case 1:
pcontacts=(person*)realloc(pcontacts,con* sizeof(person));
getInfo(&con,i,contacts);
break;
case 2:
delInfo(&con,i,contacts);
break;
case 3:
showInfo(&con,i,contacts);
break;
default:
printf("\n Error in response. Please try again: ");
break;
}
getEntry(&a);
}
printf("\n Thank you for using the Phone Book Application!\n\n");
free(contacts);
return 0;
}
void getEntry(int *a1){
int b;
printf("\n\n\n Phone Book Application\n\n 1) Add Friend\n 2) Delete Friend\n 3) Show Phone Book Entries\n 4) Exit\n\n Make a selection: ");
scanf("%d",&b);
*a1 = b;
}
void getInfo(int *con,int i,person*contacts){
printf("\n Enter first name: ");
scanf("%s",contacts[*con].fname);
printf(" Enter last name: ");
scanf("%s",contacts[*con].lname);
printf(" Enter telephone number without spaces or hyphens: ");
scanf("%d",contacts[*con].number);
(*con)++;
printf("\n Entry Saved.");
}
void delInfo(int *con,int i,person*contacts){
char delfirst[20];
char dellast[20];
printf("\n First Name: ");
scanf("%s",delfirst);
printf(" Last Name: ");
scanf("%s",dellast);
for (i=0; i<*con;i++){
if (delfirst==contacts[i].fname && dellast==contacts[i].lname){
}
}
}
void showInfo(int *con,int i,person*contacts){
char nullstr[1]={"\0"};
if (*con>0){
printf("\n Current Listings:\n");
for (i=0;i<*con;i++){
if (strcmp(nullstr,contacts[i].fname)!=0){
printf(" %s %s %i\n",contacts[i].fname,contacts[i].lname,contacts[i].number);
}
else {};
}
}
else {
printf("\n No Entries\n");
}
}