I'm trying to write a mastermind program but I'm stuck with string inputs. I try get user guess and when I try to print it it gives error I don't know why here is that part of the program
printf("Enter your guess: ");
fgets(UserGuess, 4, stdin);
int userchoice=0, i;
Lets take a look at these two lines:
char* UserGuess; fgets(UserGuess, 4, stdin);
The first declares and defines
UserGuess as an array of four pointers to
char. I.e. as four strings.
The second tries to use it as an array of
char, i.e. a single string.
This is wrong and you probably want something like
for (unsigned i = 0; i < 4; ++i) fgets(UserGuess[i], SOME_SIZE, stdin);
That of course leads to another problem, because all the pointers in
UserGuess will be null pointers (global variables are zero-initialized, which means pointers become
NULL). So you have to change the array definition as well:
Or you only want a single string of three character (plus the terminator)? Then you should change the definition of the array to
and change the output to e.g.
Then on a somewhat related note, the
fgets functions reads the newline and might add it to the string (if it fits).