Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid application of sizeof to incomplete type with a struct

Tags:

c

struct

calloc

I have a struct where I put all the information about the players. That's my struct:

struct player{
   int startingCapital;
   int currentCapital;
   int startingPosition;
   int currentPosition;
   int activePlayer; 
   int canPlay;      
};

And that's my main:

#include <stdio.h>
#include <stdlib.h>
#include "header.h"


int main(int argc, char *argv[])
{  int s,i,numOfPlayers;
   struct player *players;
    printf("Give the number of players: \n");
    scanf("%d",&numOfPlayers);

    players = (struct player *)calloc(numOfPlayers,sizeof(struct player));


   system("PAUSE"); 
  return 0;
}

I'm asking the user to give the number of players and then I try to allocate the needed memory. But I'm getting this compiler error that I can't figure out:

invalid application of `sizeof' to incomplete type `player'  
like image 489
captain Avatar asked Jan 18 '12 18:01

captain


3 Answers

It means the file containing main doesn't have access to the player structure definition (i.e. doesn't know what it looks like).

Try including it in header.h or make a constructor-like function that allocates it if it's to be an opaque object.

EDIT

If your goal is to hide the implementation of the structure, do this in a C file that has access to the struct:

struct player *
init_player(...)
{
    struct player *p = calloc(1, sizeof *p);

    /* ... */
    return p;
}

However if the implementation shouldn't be hidden - i.e. main should legally say p->canPlay = 1 it would be better to put the definition of the structure in header.h.

like image 82
cnicutar Avatar answered Oct 25 '22 12:10

cnicutar


The cause of errors such as "Invalid application of sizeof to incomplete type with a struct ... " is always lack of an include statement. Try to find the right library to include.

like image 8
oiyio Avatar answered Oct 25 '22 12:10

oiyio


Your error is also shown when trying to access the sizeof() of an non-initialized extern array:

extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'

Note that you would get an array size missing error without the extern keyword.

like image 4
alexfrigo Avatar answered Oct 25 '22 13:10

alexfrigo