Reputation: 29
typedef struct{
int moviesRented;
char title[20][20];
} Movie;
typedef struct{
int accNumber;
char name[20];
Movie movie_rental;
} Customer;
int main(){
int i;
int j;
int customerRecords;
Customer *pCustomer;
printf("Enter amount of customer records to be kept: ");
scanf("%d", &customerRecords);
pCustomer = malloc(customerRecords * sizeof(Customer));
//This will begin asking for input relating to the customer
for(i = 0; i < customerRecords; ++i){
printf("Enter account number, name, and movies rented: \n");
scanf("%d\n %s\n %d", &(pCustomer + i)->accNumber, &(pCustomer +i)->name, &(pCustomer + i)->movie_rental.moviesRented);
//for loop below is asking for multiple movie titles depending on how many movies have been rented
for( j = 0; j < (pCustomer+i)->movie_rental.moviesRented; ++j){
//asking for input of movie titles and trying to add into string array
printf("Enter Movie titles: \n");
scanf("%s", &(pCustomer+i)->movie_rental.title[j]);
}
}
printf("Displaying information: \n");
for(i = 0; i < customerRecords; ++i){
printf("Name: %s\nAcc. Number: %d\nNo. Movies Rented: %d\n",(pCustomer+i)->name, (pCustomer+i)->accNumber, (pCustomer+i)->movie_rental.moviesRented);
//for loop below does not display correctly. Only displays last entry in first iteration
for(j = 0; j < (pCustomer+i)->movie_rental.moviesRented; j++){
printf("Movies rented: %s\n", (pCustomer+i)->movie_rental.title[j]);
}
return 0;
}
Upvotes: 1
Views: 41
Reputation: 380
The problem is with your indexing in movie_rental_title
.
scanf("%s", &(ptr+i)->movie_rental.title[i]);
This line overwrites the movie name every time no matter how many movies for each customer. What you want is movie_rental.title[j]
because i will never change for the duration of the loop.
In the display you also want to change movie_rental.title[i]
to movie_rental.title[j]
Also try to keep variable names as descriptive as possible so you can avoid hard to detect errors like this.
Upvotes: 1