2010-04-05 39 views
33

我有一个结构定义为:C编程:取消引用指针不完全型误差

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

我收到以下错误:

error: dereferencing pointer to incomplete type

无论何时我尝试访问newFile中的成员。我究竟做错了什么?

+0

谢谢大家的帮助:) – confusedKid 2010-04-05 01:59:50

+0

顺便说一句,我有同样的错误,但问题是我没有包括一个特定的头文件(在一个大项目中)。 – ady 2016-05-06 18:51:39

回答

41

您尚未在第一次定义中定义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名字被放置在定义你应该做的。

+1

+1比我更快,并且使用'struct stasher_file'而不是'typedef'与在示例中OP使用类型一致。如果已经将结构定义为typedef struct {...} stasher_file,则为 – Dirk 2010-04-05 01:52:53

13

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

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

此外,你应该把结构名称放在顶部。您指定stasher_file的位置是创建该结构的实例。

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

如何为它分配空间? – confusedKid 2010-04-05 01:47:49

+0

我没有为newFile分配空间,但将stasher_file的定义更改为像您的那样,并且错误未出现。我还需要分配空间吗? – confusedKid 2010-04-05 01:55:26

+1

@confuseKid:是的,你需要像我给的那样分配空间。也请务必在完成时释放它。 – 2010-04-05 01:57:09

10

您是如何真正定义结构的?如果

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

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

尝试

typedef struct { ... } stasher_file; 

(或者,如已被别人提及):

struct stasher_file { ... }; 

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

1

为什么你得到这个错误的原因是因为你已经宣布你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; 
}; 

但要注意,虽然布莱恩R.邦迪的反应是不是你的错误信息是正确的,他是对的,你尝试写入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-终止。)

+0

;那么你可以使用malloc作为stasher_file * newFile = malloc(sizeof(stasher_file); – katta 2013-04-22 20:10:25

+0

@katta是的,但很多人认为这是一个更好的做法,而不是'T * p = malloc(sizeof * p)'。如果'p'的类型改变了,你只需要更新它的声明,而不是'malloc'站点。忘记更新'malloc'站点会默默地分配错误的内存量,可能导致缓冲区溢出 – jamesdlin 2013-04-22 23:06:59

+0

@ katta另见http://stackoverflow.com/questions/373252/c-sizeof-with-a-type-or-variable – jamesdlin 2013-04-22 23:34:30

5

上面的情况是针对一个新项目。编辑已建立好的库的分支时,我遇到了这个错误。

typedef包含在我正在编辑的文件中,但结构不是。

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

如果你以类似的方式运行它,请查找结构被编辑的其他地方并在那里尝试。

+1

+1,因为这句话让我走上正轨! – Ludo 2013-10-10 11:09:31

相关问题