Reputation: 29
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
char* UserGuess[4];
void *Guess()
{
long i;
printf("Enter your guess: ");
for(i=0;i<4;i++)
{
fgets(UserGuess, 4, stdin);
}
return UserGuess;
}
int main()
{
int userchoice=0, i;
while(userchoice!=2)
{
Guess();
printf("%s\n", UserGuess[0]);
break;
}
}
Upvotes: 1
Views: 77
Reputation: 409196
Lets take a look at these two lines:
char* UserGuess[4];
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:
char UserGuess[4][SOME_SIZE];
Or you only want a single string of three character (plus the terminator)? Then you should change the definition of the array to
char UserGuess[4];
and change the output to e.g.
printf("%s\n", UserGuess);
Then on a somewhat related note, the fgets
functions reads the newline and might add it to the string (if it fits).
Upvotes: 1
Reputation: 19
You can probably use scanf("%d",&n) where n is an integer instead of going this route.
Upvotes: 0
Reputation: 134346
In your code, UserGuess
is an array of pointer-to-char
, but all the elements, are invalid (NULL
). You need to allocate memory to them before you can write into team.
That said, with fgets()
, you need to pass the individual elements of the array.
Something like
char UserGuess[4][32];
and
for(i=0;i<4;i++)
{
fgets(UserGuess[i], 32, stdin);
}
can be a good start.
Upvotes: 0