I have this program that almost works. I have a typedef struct called Customer with several fields. Two of them are char* which will be to store strings. I have an array of Customer, but whenever I add an entry to the array, both the char* fields get overwritten. So every entry has the same name and address as the last one entered. I used calloc(), but I think the problem has something to do with pointers. Anyways, here's some of my code.
Code:
#include <stdio.h>
#include <string.h>
#include "lab11_funcs.h"
#define MAX_CUSTOMERS 10
int main(void)
{
char menuSel;
Customer customer[MAX_CUSTOMERS];
int count,i;
count = 0;
for(i=0;i<MAX_CUSTOMERS;i++) customer[i].init=0;
while((menuSel=display_menu())!='Q') {
switch(menuSel) {
case 'A':
customer[count]=addCustomer();
printf("%s\n",customer[count++].name);
break;
case 'M':
printf("Select the customer number of the customer info you would like to modify:\n");
while(getchar()!='\n');
scanf("%d",&i);
if (customer[i].init==9) customer[i]=modifyCustomer(customer[i]);
else fprintf(stderr,"The customer number does not exist");
break;
case 'D':
Display(customer);
break;
default:
fprintf(stderr, "Invalid menu choice. Please try again.\n");
}
}
return 0;
}
....
//lab11_funcs.h
#ifndef SOMETHING
#define SOMETHING
typedef struct {
char ID[10];
char *name;
unsigned int num;
char *address;
char phoneNumber[10];
int init;
} Customer;
#endif
char display_menu(void);
Customer addCustomer(void);
Customer modifyCustomer(Customer mod_cust);
void Display(Customer cust_list[]);
.......
// part of lab11_funcs.c
Customer addCustomer(void)
{
free(customer.name);
free(customer.address);
printf("Please enter the customer's ID:\n");
fgets(customer.ID, 10, stdin);
//while(getchar()!='\n');
customer.ID[strlen(customer.ID)-1] = '\0';
//customer.ID[sizeof(customer.ID)-1] = '\0';
//printf("%s\n", customer.ID);
fflush(stdin);
printf("Please enter the customer's name:\n");
customer.name=(char*)calloc(BUFSIZ,sizeof(char));
fgets(customer.name, BUFSIZ, stdin);
customer.name[strlen(customer.name)-1] = '\0';
printf("%s\n", customer.name);
//while(getchar()!='\n');
fflush(stdin);
printf("Please enter the customer's number:\n");
scanf("%d",&customer.num);
//printf("%s\n", customer.num);
while(getchar()!='\n');
fflush(stdin);
printf("Please enter the customer's address:\n");
customer.address=(char*)calloc(BUFSIZ,sizeof(char));
fgets(customer.address, BUFSIZ, stdin);
customer.address[strlen(customer.address)-1] = '\0';
printf("%s\n", customer.address);
//while(getchar()!='\n');
fflush(stdin);
printf("Please enter the customer's phone number (only digits):\n");
fgets(customer.phoneNumber, 11, stdin);
customer.phoneNumber[strlen(customer.phoneNumber)-1] = '\0';
// while(getchar()!='\n');
fflush(stdin);
customer.init=9;
return customer;
}
Thanks a lot if you can help.