错误:在c中重新定义typedef

yot*_*moo 2 c struct

我们在学校有一个作业,我们有一个头文件,我们需要实现它.标题定义:

typedef struct Board* BoardP;
Run Code Online (Sandbox Code Playgroud)

据我所知,BoardP是指向struct Board的指针.无论如何,我的实现是:

typedef struct Board
{
    int width;
    int height;
    char *board;
} *BoardP;
Run Code Online (Sandbox Code Playgroud)

但我一直得到:

Board.c:21: error: redefinition of typedef ‘BoardP’
Board.h:4: note: previous declaration of ‘BoardP’ was here
Run Code Online (Sandbox Code Playgroud)

关于为什么会这样的想法?谢谢!

编辑:另一个问题.正如您所看到的,我的struct包含一个字符数组.当我写一个构造函数时,我应该首先初始化(malloc(sizeof(height*width))数组然后结构吗?如何使用free()?我应该首先释放数组然后结构吗?谢谢

cni*_*tar 5

typedef从定义中删除.

struct Board
{
    int width;
    int height;
    char *board;
};
Run Code Online (Sandbox Code Playgroud)

结构是一个结构; 它不像你总是要typedef这样.说实话,我只是typedef structs为了不透明的指针.

来自style(9):

避免对结构类型使用typedef.Typedef是有问题的,因为它们没有正确隐藏它们的底层类型; 例如,您需要知道typedef是结构本身还是指向结构的指针.此外,它们必须恰好声明一次,而不完整的结构类型可以根据需要多次提及.