Hasan Bilal Adak Hasan Bilal Adak - 4 months ago 8
C Question

Getting input as string and Printing

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

Answer

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

Comments