gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:24:10 26 4
gpt4 key购买 nike

所以我想说,我已经搜索了很多这个问题的答案,但我觉得没有人真正回答了我的问题(或者我只是不明白,可能是后者)。我对 C 还比较陌生,所以我对这个可能是相当明显的答案表示歉意。

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

struct card{ 
char suit;
int value;
};

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

最佳答案

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

关于c - 我如何将结构作为元素传递到 C 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53706244/

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