繁体   English   中英

C 编程:取消引用指向不完整类型错误的指针

[英]C programming: Dereferencing pointer to incomplete type error

我有一个结构定义为:

struct {
 char name[32];
 int  size;
 int  start;
 int  popularity;
} stasher_file;

以及指向这些结构的指针数组:

struct stasher_file *files[TOTAL_STORAGE_SIZE];

在我的代码中,我创建了一个指向结构的指针并设置其成员,并将其添加到数组中:

 ...
 struct stasher_file *newFile;
 strncpy(newFile->name, name, 32);
 newFile->size = size;
 newFile->start = first_free;
 newFile->popularity = 0;
 files[num_files] = newFile;
 ...

我收到以下错误:

错误:取消引用指向不完整类型的指针

每当我尝试访问newFile的成员时。 我究竟做错了什么?

您还没有通过第一个定义定义struct stasher_file 您定义的是无名结构类型和该类型的变量stasher_file 由于代码中没有struct stasher_file这样的类型的定义,编译器会抱怨类型不完整。

为了定义struct stasher_file ,您应该按如下方式完成

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

注意stasher_file名称放在定义中的位置。

您正在使用指针newFile而不为其分配空间。

struct stasher_file *newFile = malloc(sizeof(stasher_file));

您还应该将结构名称放在顶部。 您指定stasher_file的位置是创建该结构的实例。

struct stasher_file {
    char name[32];
    int  size;
    int  start;
    int  popularity;
};

你是如何实际定义结构的? 如果

struct {
  char name[32];
  int  size;
  int  start;
  int  popularity;
} stasher_file;

将被视为类型定义,它缺少typedef 如上所述,您实际上定义了一个名为stasher_file的变量,其类型是一些匿名结构类型。

尝试

typedef struct { ... } stasher_file;

(或者,正如其他人已经提到的):

struct stasher_file { ... };

后者实际上匹配您对该类型的使用。 第一种形式要求您在变量声明之前删除struct

上面的案例是针对一个新项目。 我在编辑一个完善的库的fork时遇到了这个错误。

typedef包含在我正在编辑的文件中,但结构却没有。

最终的结果是我试图在错误的地方编辑结构。

如果您以类似的方式遇到此问题,请查找编辑结构的其他位置并在那里进行尝试。

您收到该错误的原因是您已将struct声明为:

struct {
 char name[32];
 int  size;
 int  start;
 int  popularity;
} stasher_file;

这不是声明stasher_file类型。 这是声明一个匿名 struct类型,并且正在创建一个名为stasher_file的全局实例。

你的意图是:

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

但请注意,虽然Brian R. Bondy对您的错误消息的回答不正确,但他是正确的,您正试图在没有为其分配空间的情况下写入struct 如果你想要一个指向struct stasher_file结构的指针数组,你需要调用malloc来为每个结构分配空间:

struct stasher_file *newFile = malloc(sizeof *newFile);
if (newFile == NULL) {
   /* Failure handling goes here. */
}
strncpy(newFile->name, name, 32);
newFile->size = size;
...

(顺便说一句,使用strncpy时要小心;不能保证NUL终止。)

原因是您没有声明类型struct stasher_file ,而是定义了一个 struct 变量stasher_file

C ,结构的声明:

    struct structure-tag {
        member1
        member2
        ...
    };

structure-tag是跟在关键字struct之后的可选名称。 声明后,您可以定义一个变量:

    struct structure-tag var1, *var2;

此外,您可以同时进行声明和定义,例如:

    struct structure-tag {
        member1
        member2
        ...
    } var1, *var2;

所以在你的情况下,你可以试试这个:

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
} *files[TOTAL_STORAGE_SIZE];

struct stasher_file *newFile = malloc(sizeof(struct stasher_file));

... other code ...

就这样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM