Alieldin Ayman
Alieldin Ayman

Reputation: 3

Variable returned by Reference from a function gives weird values

I've been working on a hangman game lately, and this function supposedly checks for a letter that the user inputs in an array (Containing a pre-defined word such as "BUILDING") and adds on a Counter (Count) if the letter exists or decreases the lives (Which start at 5 -defined in the main function-) if it doesn't exist.

Now the Count variable works fine but the Lives variable keeps decreasing anyways, even if the letter exists and it doesn't just decrease by 1 but by bigger amounts resulting in rather big negative numbers.

Here's the code, thanks in advance:

void Checkf(char X,int r,int Length,char *Hidden, int *Lives,int *Count)
{
int i;
for (i=0;i<Length;i++)
{
    if (X==Words[r][i] && Hidden[i]=='*')
    {
        Hidden[i] = X;
        *Count = *Count + 1;
    }
    else if (X!=Words[r][i] && Hidden[i]=='*')
    *Lives = *Lives - 1;
}
}

Upvotes: 0

Views: 40

Answers (1)

SwedishOwlSerpent
SwedishOwlSerpent

Reputation: 355

That behavior occurs because you (optionally) decrease the value of Lives on each iteration of the loop. You can add a variable that indicates whether the letter was found or not, and then decrease the value of Lives after the loop ends, like this:

void Checkf(char X,int r,int Length,char *Hidden, int *Lives,int *Count)
{
int i;
unsigned char found = 0;
for (i=0;i<Length;i++)
{
    if (X==Words[r][i] && Hidden[i]=='*')
    {
        Hidden[i] = X;
        *Count = *Count + 1;
        found = 1;
    }
}
if (!found)
{
    *Lives -= 1;
}
}

Upvotes: 2

Related Questions