关于二维字符数组用C实践逻辑

问题描述 投票:1回答:1
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( 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;
    }
c
1个回答
1
投票

问题是,在movie_rental_title您的索引。

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

这条线路将覆盖每一次电影的名字,不管多少部电影为每一个客户。你想要的是movie_rental.title[j]因为我永远不会为循环的持续时间而改变。

在显示你也想改变movie_rental.title[i]movie_rental.title[j]

也尽量保持变量名称描述尽可能这样就可以避免难以检测这样的错误。

© www.soinside.com 2019 - 2024. All rights reserved.