0

so just wanna start by saying I've searched around quite a lot for the answer to this but I felt none really answered my question (or I just didn't understand it, probably the latter). I'm relatively new to C so I apologise for what might be quite an obvious answer.

I want to create a deck of cards as an array of 52 elements, but I want each element to be a structure that holds both suit and value. I understand how I would create the structure, something like:

struct card{ 
  char suit;
  int value;  
};

What confuses me, however, is how I would pass each structure as an element into an array. I've been trying to think for a long time and I just can't think of it. Surely passing this structure into an array wouldn't be possible, because it is composed of both an int and a char value? Of course I could just use a for loop to pass each value into a new array such as int deck[52]; but not sure how I'd pass the char suit as well - is this possible?

James Corin
  • 35
  • 1
  • 5
  • are you asking how to write `struct card deck[52];`? – Chris Turner Dec 10 '18 at 13:04
  • *"how I would pass each structure as an element into an array"* - pass it to *what* ? A function ? Or are you asking how to declare an array of `struct card` ? Exactly how you would declare an array to anything else: `Type arr[size];`, in this case `struct card deck[52];` – WhozCraig Dec 10 '18 at 13:06

1 Answers1

0

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

Actually, it is possible:

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)
}

So in this example, myCards[5] = someCard; basically copies the element to the other element. In other words, it copies both the respective char and int.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • Hey thank you, this answered my question. Just another question (sorry) but in your example someCard = {1, 20}, which is referring to the value and which is referring to the suit? does it go in the order of the struct? And if both, how would I access each individually? – James Corin Dec 10 '18 at 13:18
  • That's right, it goes in `struct` order, so the `suit` is `1` and the `value` is `20` in this example. You can individually access the values like `myCards[5].suit = 3;` or `myCards[5].value = someCard.value;`, for instance. – Blaze Dec 10 '18 at 13:22
  • 1
    Semantics... _passing this structure into an array_ is not what is happening here. What you are demonstrating is that a `struct` array element can be updated with an instance of a `struct` via assignment. _Passing a struct_ what happens in a function argument. – ryyker Dec 10 '18 at 13:37