I'm working on this code, and it's not finished yet. But while testing the add new contacts function and printing function, I get this strange output. Everythin looks ok as long as I'm not adding more than one contact. What am I doing wrong here?
//Libraries:
#include <stdio.h>
#include <stdlib.h>
//Function prototypes
int showMenu(); //Shows user options
//Main function
int main() {
//Variable declerations
int i = 0;
int iOption = 0;
int iContacts = 0;
char *cPhoneBook_name;
int *iPhoneBook_nr;
cPhoneBook_name = (char *) calloc(1, 80 * sizeof(char));
iPhoneBook_nr = (int *) calloc(1, sizeof(int));
do {
//Memory check
if(cPhoneBook_name == NULL || iPhoneBook_nr == NULL){
printf("\nOut of Memory!\n");
return;
}
//Show menu
iOption = showMenu();
switch (iOption) {
case 1: //Add contact
printf("\nEnter name:\n");
scanf("%s", &cPhoneBook_name[iContacts]);
printf("\nEnter number:\n");
scanf("%d", &iPhoneBook_nr[iContacts]);
cPhoneBook_name = realloc(cPhoneBook_name, 80 * sizeof(char));
iPhoneBook_nr = realloc(iPhoneBook_nr, sizeof(int));
iContacts += 1;
break;
case 2: //Modify contact
//Code here
break;
case 3: //Show contacts
for(i = 0 ; i < iContacts ; i++) {
printf("\n%s %d\n", &cPhoneBook_name[i], iPhoneBook_nr[i]);
}
break;
case 4: //Free memory (delete contacts)
free(cPhoneBook_name);
free(iPhoneBook_nr);
break;
}
}while(iOption != 5);//Exit if iOption is 5;
system("clear");
return 0;
}
//Function definition - showMenu()
int showMenu() {
int iOption = 0;
//system("clear");
printf("\n Phone book \n");
printf("------------------------\n");
printf("1. Add new contact.\n");
printf("2. Edit existing contact\n");
printf("3. Show contact(s)\n");
printf("4. Clear phone book\n");
printf("5. Exit\n");
printf("------------------------\n");
printf("Option --> ");
scanf("%d", &iOption);
return iOption;
}
//---------------------------------------------------------