C练习中与2D字符数组有关的逻辑

时间:2019-02-05 16:24:54

标签: c

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));

//这将开始要求与客户有关的输入

    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循环根据要租看的电影要求提供多个电影标题

        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循环无法正确显示。仅显示第一次迭代中的最后一个条目

            for(j = 0; j < (pCustomer+i)->movie_rental.moviesRented; j++){ 
               printf("Movies rented: %s\n", (pCustomer+i)->movie_rental.title[j]);
            }
        return 0;
    }

1 个答案:

答案 0 :(得分:1)

问题出在您在movie_rental_title中建立索引。

scanf("%s", &(ptr+i)->movie_rental.title[i]);

无论每位客户有多少部电影,此行都会覆盖电影名称。您想要的是movie_rental.title[j],因为在循环期间我永远都不会改变。

在显示中,您还想将movie_rental.title[i]更改为movie_rental.title[j]

还尝试使变量名尽可能地具有描述性,这样可以避免难于发现此类错误。