sizeof 对具有结构的不完整类型的无效应用 [英] Invalid application of sizeof to incomplete type with a struct

查看:17
本文介绍了sizeof 对具有结构的不完整类型的无效应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构体,我在其中放置了有关玩家的所有信息.这是我的结构:

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;      
};

这就是我的主要内容:

#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'  

推荐答案

这意味着包含 main 的文件无权访问 player 结构定义(即不知道长什么样).

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

尝试将它包含在 header.h 中,或者创建一个类似构造函数的函数,如果它是一个不透明的对象,它就会分配它.

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

如果您的目标是隐藏结构的实现,请在可以访问该结构的 C 文件中执行此操作:

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;
}

然而,如果实现不应该被隐藏 - 即 main 应该合法地说 p->canPlay = 1 最好把结构的定义在 header.h 中.

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.

这篇关于sizeof 对具有结构的不完整类型的无效应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆