Here's what I get when I compile your code at maximum warning level:
Code:
$ make foo
gcc -Wall -ggdb3 -pedantic -std=gnu99 -O0 -o foo foo.c -lm -lpthread -lrt
foo.c: In function ‘ret_turn’:
foo.c:25:9: warning: value computed is not used [-Wunused-value]
*turn++;
^
foo.c: In function ‘main’:
foo.c:49:9: warning: unused variable ‘winner’ [-Wunused-variable]
int winner = 0;
^
foo.c:48:9: warning: unused variable ‘highest_score’ [-Wunused-variable]
int highest_score = 0;
^
That first warning points you (indirectly) to the error. It's telling you that you never use (store, print, use in a different calculation), the result of *turn++.
Check your handy
operator precedence chart. You'll notice that ++ (postfix increment) is higher precedence than * (dereference). That means it applies first. So your code takes the address stored in the turn pointer, increments it (points it to a difference piece of memory
1) and then dereferences (gets the value from) that new address. But you don't do anything with that value. What you really are trying to do is the reverse. Get the value stored at the address in turn, and increment that. Force the order you want with parens:
If you're ever unsure about stuff like this, there's no real harm in being a bit more explicit:
Code:
*turn += 1;
// or
*turn = *turn + 1;
Since your function is returning void, you can make it return int and return the turn number that way.
You have a few other issues with your code, even after fixing that:
- Your code behaves as though there is one extra player; if I enter 2 players, it thinks there are 3.
- Your code doesn't stop when all players are out of lives.
- cont is set to false in ret_turn, but that value is not reflected in the main function, i.e. you pass cont by value, you should pass it by reference (same as you do turn).
- Don't use magic numbers, define constants with sensible names: MAX_PLAYERS, MIN_PLAYERS, MAX_PLAYER_NAME, etc.
- fgets is better for reading in player names, it allows you to specify a max length. scanf does let you do this, but it is less flexible, and more prone to writing past the end of your string1.
- Break your code up better into functions. Have one function that gets game parameters (num players, player names, num lives). Have another that determines if the game is over. Have one that gets the next player who is still alive. Give them sensible names like: get_game_parameters, is_game_over, get_next_player.
- strcpy(Player[i].p_name, "0"); doesn't make a blank string, it gives every player the name "0" (a one-char name consisting of the digit zero). You probably want strcpy(Player[i].p_name, ""); or Player[i].p_name[0] = '\0'; to make them empty strings.
1 This means you access memory you don't own. This results in
undefined behavior, which is bad.