#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int number;
struct player *next;
}player;
player *newPlayer;
player *firstPlayer;
player *currentPlayer;
int main(void)
{
newPlayer = malloc(sizeof(player));
firstPlayer = newPlayer;
currentPlayer = newPlayer;
currentPlayer->next = NULL;
printf("Please enter Head: ");
scanf("%d", ¤tPlayer->number);
newPlayer = malloc(sizeof(player));
currentPlayer->next = newPlayer;
currentPlayer = newPlayer;
currentPlayer->next = NULL;
printf("Please enter second element: ");
scanf("%d", ¤tPlayer->number);
currentPlayer = firstPlayer;
while (currentPlayer)
{
printf("%d ", currentPlayer->number);
currentPlayer = currentPlayer->next;
}
printf("\n");
}
The code compiles correctly, but I get these warnings:
warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
currentPlayer->next = newPlayer;
and
warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
currentPlayer = currentPlayer->next;
Why is that and how can I fix it?
Thank you in advance :)
When defining your struct, you omitted the struct name. By doing that, you actually created a generic struct, which can be referred to only by its typedef (alias).
typedef struct
{
int number;
struct player *next;
} player;
In this definition, player is just an alias to this generic struct.
To fix that, add the word player to the first line:
typedef struct player
{
int number;
struct player *next;
} player_t;
Now, you're able to refer the struct either by struct player
, or by player_t
.
Always remember that the keyword typedef
is just for us, the programmers, for readability. Don't count on it to do some extra work.
EDIT: As mentioned in the comments, it's possible to use typedef struct player player
and refer to the struct either by struct player
or just plain player
.