gpt4 book ai didi

类 : Passing struct array giving strange result 的 C 程序

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

我已经设置了几个 printf 语句来查找问题,但我仍然一无所知。

基本上,我正在创建包含 12 个结构席位的阵列平面。

然后我分配平面数据中的每个结构。此时一切看起来都很好。

然后我将该数组传递给 numberEmptySeats,突然间 plane[0].seatID 丢失了,而不是最初分配的 1。

请帮助我理解为什么会这样。

------------电流输出------------

1
Entering numberEmptySeats
1123456789101112
Seats Available: 12

------------期望的输出------------

1
Entering numberEmptySeats
1
Seats Available: 12

代码:

#include<stdio.h>
#include<string.h>
#define SEATS 12

struct seat {
int seatID;
int reserved;
char firstName[20];
char lastName[20];
};

void resetPlane(struct seat ar[],int seats);
void numberEmptySeats(struct seat ar[],int seats);

int main()
{
struct seat plane[SEATS];
resetPlane(plane,SEATS);
printf("%d\n",plane[0].seatID);
numberEmptySeats(plane,SEATS);
}

void resetPlane(struct seat ar[],int seats)
{
int i;
for(i=0;i<seats;i++)
{
ar[i].seatID = i+1;
ar[i].reserved = 0;
strcpy(ar[i].firstName,"Unassigned");
strcpy(ar[i].lastName,"Unassigned");
}
}

void numberEmptySeats(struct seat ar[],int seats)
{
int i,j=0;
printf("Entering numberEmptySeats\n");
printf("%d",ar[0].seatID);
for(i=0;i<seats;i++)
{
if (ar[i].reserved == 0)
{
printf("%d",ar[i].seatID);
j++;
}
}
printf("\nSeats Available: %d\n",j);
}

最佳答案

在打印第一个 ID 一次(也没有换行符)之后,您正在打印每个可用座位的 ID,之后没有换行符。

void numberEmptySeats(struct seat ar[],int seats)
{
int i,j=0;
printf("Entering numberEmptySeats\n");
printf("%d\n",ar[0].seatID); // added newline
for(i=0;i<seats;i++)
{
if (ar[i].reserved == 0)
{
// printf("%d",ar[i].seatID); // drop the extra output
j++;
}
}
printf("\nSeats Available: %d\n",j);
}

关于类 : Passing struct array giving strange result 的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917376/

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