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

标签 c arrays function struct

我已经设置了几个 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/

相关文章:

c - C中头文件中带有struct参数的函数声明

C - 结构中的字符串返回整个数组

C:打印数组中某个点的水平、垂直和倾斜值

c - 字符串长度与数组长度不同?

arrays - 使用变量在 bash 中传递 grep 模式

ios - 如何从coredata swift中随机选择一个元素

javascript - 按排序顺序将数组数组减少为数组

python - 如何将 `lambda` 对象转换为 `function` 对象以在 Python 中进行酸洗?

JavaScript:函数链接还是属性访问?

javascript - if/else 语句中的语法错误