-7

I have 3 users that need to choose between x and o. I ask user 1 for their choice and then genrate choice for user 2 and user 3. MY 3 chars are choice1, choice2, choice3. When called in my code the output is the letter chosen/generated. example: user 1:x user 2: o user 3: x

How would i be able to create an array that holds these 3 char values?

char choice_value [2] = 'x' , 'o'
char choices [3] = 'choice1','choice 2','choice3'

Am I on the right track?

L M
  • 1
  • 2
  • 3
    Remember a `char` is just a single character. `char c = 'o';` for example. To make an array of characters, you'd do something like `char arr[3] = {'x', 'o', 'x'};` And then you can change the middle one to an `x` with `arr[1] = 'x';` – Gillespie Apr 11 '23 at 19:16
  • 2
    _"Am I on the right track?"_ No, you're completely off the track. – πάντα ῥεῖ Apr 11 '23 at 19:20
  • There is a list of good books [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Apr 11 '23 at 20:06

1 Answers1

-1

If you want an array of three strings, and you want to use C-style strings, you have two choices. First would be an array of char pointers.

char *choices[3] = {"choice1", "choice2", "choice3"};

Or you can declare an array of arrays. We'll give each string 9 characters to work with plus room for the null terminator.

char choices[3][10] = {"choice1", "choice2", "choice3"};

The difference is significant. In the first case, each element in the array is a pointer to a character. If you initialize it with string literals, note that you can't modify those. If you don't, bear in mind that you need to make sure they're pointing to valid memory.

In the second option, the memory is statically allocated. Those strings can never be longer than 9 characters without undefined behavior coming into play.

Better would be an array of std::string if you are using C++.

std::string choices[3] = ...

Better than that would be to either use std::vector or std::array.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 2
    In the first case, you have to use `const char*` instead of `char*`, as a string literal is a `const char[]` array and so can't can't be assigned to a non-const pointer. – Remy Lebeau Apr 11 '23 at 19:22