Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c - Invalid application of sizeof to incomplete type with a struct

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: 
");
    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'  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...