我如何将结构作为元素传递到 C 中的数组中

How would I pass structs as elements into an array in C

所以我只想说我已经搜索了很多关于这个问题的答案,但我觉得 none 确实回答了我的问题(或者我只是不明白,可能是后者) .我是 C 语言的新手,所以我为这个可能很明显的答案道歉。

我想将一副纸牌创建为包含 52 个元素的数组,但我希望每个元素都是一个包含花色和点数的结构。我了解如何创建结构,例如:

struct card{ 
  char suit;
  int value;  
};

然而,令我困惑的是我如何将每个结构作为一个元素传递到数组中。我想了很久,就是想不出来。肯定不可能将此结构传递到数组中,因为它由 int 和 char 值组成?当然,我可以只使用 for 循环将每个值传递到一个新数组中,例如 int deck[52];但不确定我如何通过 char suit - 这可能吗?

Surely passing this structure into an array wouldn't be possible, because it is composed of both an int and a char value?

其实是可以的:

struct card {
    char suit;
    int value;
};

int main() {
    struct card myCards[52];    // the deck of cards
    struct card someCard = { 1, 20 }; // an instance of the card
    myCards[5] = someCard;  // setting an element of the deck to the card (the rest stays uninitialized)
}

所以在这个例子中,myCards[5] = someCard;基本上是将元素复制到另一个元素。换句话说,它复制了各自的 charint.