C:typedef 结构体。函数无法识别结构类型



,所以情况是...我有三个文件:main.c |functions.h |functions.c

在main.c中我创建了一个结构,并将其定义为一种称为"得分"的新类型:

typedef struct
{
    int iWins = 0, iWins2 = 0, iTies = 0;
} score;

i然后创建了一个"得分"的实例,称为 SpScore

score SpScore;

我将其传递给一个函数(在main.c中),称为 spgame_f

spgame_f(SpScore);

spgame_f位于functions.c中。现在编译时会给我错误:

unknown type name: score

我还尝试在" functions.c"顶部定义结构,这给了我错误:

expected ':', ',', ';', '}' or '__attribute__' before '=' token" (error for the line where the integer's are declared in the struct).

我在做什么错?

您无法在typedef中初始化struct成员,这是没有意义的。您应该这样做:

typedef struct
{
    // No = 0 here
    int iWins, iWins2, iTies;
} score;
int main() {
    // Initializing to 0 here
    score SpScore = {0,0,0};
}

此外,您应该将typedef放入.h标头文件中,并将其包含在所有使用该定义的.c/.h文件中,否则您将获得"未知类型" ...错误:

Score.h

#ifndef __SCORE_H__
#define __SCORE_H__
typedef struct
{
    // No = 0 here
    int iWins, iWins2, iTies;
} score;
#endif

和:

main.c等。

#include "score.h"
int main() {
    score pScore = {0,0,0};
    return 0;
}

最新更新