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

标签 c arrays struct element

所以我想说,我已经搜索了很多这个问题的答案,但我觉得没有人真正回答了我的问题(或者我只是不明白,可能是后者)。我对 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/

相关文章:

java - JNI 中的 GetByteArrayRegion

python - 在 Python 中将点的平面列表转换为二维 System.Array 类型 Array[Array[Point]]

java - 将用户定义的对象添加到数组 - 并返回 2 个对象之一

objective-c - 在 Swift 中从 vDSP DSPSplitComplex 创建 Metal 缓冲区

go - 根据值匹配数组

使用内存地址在不带指针的 C 函数中更改数组

c - 可变长度的字符串到int数组?

c - C 中的二维数组和警告 : assignment makes integer from pointer without a cast

python - 最长递增唯一子序列

c# - c#中的结构和属性问题