I am writing this program and using calloc. My next step is to add realloc for every new entry added.
But i do not understand why when I set
Code:
ent1 = (ent *)calloc(1, sizeof(ent));
this, if I choose to add a new entry, I can. I thought the above code would only let me use enough memory(one array of my struct) for one of my typedef struct??
I seem to be able to add new entries into the memory space i thought would only hold 1 type (ent).
I must be confused about how calloc works, so if anyone can explain I would be grateful.
Code:
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
typedef struct entry{
char name[25];
int num;
}ent;
void addEntry(ent *);
void printEntry(ent*);
int entries = 0;
int main(){
ent *ent1;
ent *newEnt1;
int choice = 0;
ent1 = (ent *)calloc(1, sizeof(ent));
if (ent1 == NULL) {
return; //calloc is not successful
}//end if
do {
printf("\n1\tAdd Entry.\n");
printf("2\tPrint list.\n");
printf("3\tQuit.\n");
printf("Enter choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
addEntry(ent1);
entries += 1;
break;
case 2:
printEntry(ent1);
break;
default:
break;
}//switch
} while (choice != 3);
return 0;
free(ent1);
}//main
void addEntry(ent * ent2){ //ent2 accepts ent1
printf("\nEnter name: \n");
scanf("%s", ent2[entries].name);
//fgets(ent2[entries].name, 25, stdin);
printf("Enter Phone number: \n");
scanf("%d", &ent2[entries].num);
}//end func def add
void printEntry (ent * ent2){
int x;
for (x=0; x<entries; x++) {
printf("\nName: %s\n", ent2[x].name);
printf("Phone number: %d\n", ent2[x].num);
}//for
}//end func def prlst