结构体和变量循环C语言

struct and variable looping C language

#include <stdio.h>

struct Car {
  char brand[50];
  char model[50];
  int year;
};

int main() {
  struct Car car1 = {"BMW", "X5", 1999};
  struct Car car2 = {"Ford", "Mustang", 1969};
  struct Car car3 = {"Toyota", "Corolla", 2011};

  printf("%s %s %d\n", car1.brand, car1.model, car1.year);
  printf("%s %s %d\n", car2.brand, car2.model, car2.year);
  printf("%s %s %d\n", car3.brand, car3.model, car3.year);

  return 0;
}

/*
BMW X5 1999
Ford Mustang 1969
Toyota Corolla 2011
*/

这里的结构只有 3 个变量(car1、car2、car3)。但是,如果它有很多汽车,我如何使用循环来编写相同的代码(打印所有值)?

您需要 struct Car.

的数组

它的工作原理与任何其他数组几乎相同,不同之处在于每个元素现在都有额外的字段,即结构上的字段。

这是一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 100

struct Car {
  char brand[50];
  char model[50];
  int year;
};


int main(void) {
    struct Car cars[SIZE];

    for (int i = 0; i < SIZE; i++) {
        // Initialize
        strcpy(cars[i].brand, "BMW"); // or any other brand
        strcpy(cars[i].model, "X5");

        cars[i].year = 1999;
    }

    for (int i = 0; i < SIZE; i++) {
        // Print
        printf("Car %d:\n", i + 1);
        printf("%s %s %d\n", cars[i].brand, cars[i].model, cars[i].year);
    }

    return 0;
}

你需要一个 Car 的数组,像这样

#include <stdio.h>

struct Car {
  char brand[50];
  char model[50];
  int year;
};

int main() {
    struct Car cars[] = {
        {"BMW", "X5", 1999},
        {"Ford", "Mustang", 1969},
        {"Toyota", "Corolla", 2011},
        {"Mercedes", "C197", 2010 }
    };

    for(size_t i = 0; i < sizeof(cars)/sizeof(cars[0]); ++i) {

        printf("%s %s %d\n", cars[i].brand, cars[i].model, cars[i].year);
    }

    return 0;
}