I have few questions connected with struct and typedef, there is piece of code and I have marked some places where I’m not sure if the syntax is correct. I use Eclipse editor and it shows me when there is problem in compilation. I just don’t understand why is sometimes keyword struct needed and sometimes not. I may have also some mistakes of using this keyword. So plese help me to understand it.
let’s have struct
typedef struct player
{
char *name;
int gameId;
int points;
int socketfd; //socket descriptor of player
int state;
} player_struct;
lets have another struct
#define PLAYERSLEN 2
typedef struct game{
struct player_struct *players[PLAYERSLEN]; //PLACE1
//some code
} game_struct;
let’s have function
player_struct *create_player() //PLACE2
{
player_struct *player; //PLACE3
//alokace pameti
player = (player_struct *) malloc(sizeof(player_struct)); //PLACE4
//PLACE5
player->gameId = -1;
player->points = 0;
player->state = 0;
return player;
}
let’s have function? In fact what does this definition mean?
void *( player_struct *player) //PLACE6
{
//some code
}
Questions references:
PLACE1 – is this correct? why can’t I use just player_struct *players[PLAYERSLEN]; ??
PLACE2 – it looks like there is not needed struct before player_struct , is it correct? why?
PLACE3 – it looks like there is struct also not needed, is it correct? why?
PLACE4 – it looks like there is struct also not needed, is it correct? why?
PLACE4 & PLACE5 I may should handle errors there, cause there is malloc so I should probably put all the line with PLACE4 to if and if the malloc fails I should put at PLACE 5 free(player). Am I right?
PLACE6 what could have mean this function or whatever it is? The code inside brackets which is not included here should delete the player .. I just don’t understand the syntax of wrote function – what does it mean?
PLACE6 – again similar as previous why is not necessary put the keyword struct before player_struct at this line? is it correct?
Really thanks you for your time.
player_structis a typedef forstruct player. You don’t need thestructkeyword in this case.player_structwhich meansstruct player.malloc()returns NULL. In addition, don’t cast the return value frommalloc(). Doing so can hide#includeerrors.structbecause of thetypedef– same as above.You may find this all makes more sense if you remove the words
typedef,player_struct, andgame_structfrom your code entirely. Then once you get used to how that all works, you can reintroduce thetypedefsand maybe cut down on some typing. As a quick example, you can break down your first definition into its components:Maybe that will help you make sense of it?