gpt4 book ai didi

c - C实践中二维字符数组的逻辑

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:02 24 4
gpt4 key购买 nike

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

最佳答案

问题在于您在 movie_rental_title 中的索引。

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

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

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

同时尽量使变量名尽可能具有描述性,这样您就可以避免像这样难以检测的错误。

关于c - C实践中二维字符数组的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54538801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com