c++ - 带有指针 : Member reference base type (. ..) 的函数不是结构或 union

标签 c++ c data-structures clang

我遇到以下错误:

"error: member reference base type 'start' (aka 'struct no_start *') is not a structure or union".

所以,我有很多结构,例如:

typedef struct no_start * start;

struct no_start{
   prog * node_program;
};

函数如下:

start * insert_start(prog * program){

   start * data = (start *) malloc(sizeof(start));

   data->node_program = program;

   return data;

}

我有一个文件functions.c,其中包含这样的简单函数,一个文件structs.h,其中包含结构,最后一个functions.h,我在其中声明第一个文件的函数。

我不明白为什么会出现这个错误。对于每个函数,我得到的错误数量与分配的错误数量一样多。

最佳答案

展开 typedef,你会看到出了什么问题:

struct no_start ** data = (struct no_start **) malloc(sizeof(struct no_start*)); 
data->node_program = program; // Nope; *data is a pointer

你可以使用

start data = malloc(sizeof(*data));
data->node_program = program;

但通常最好避免“指针类型定义”,除非它们用于不透明类型(即隐藏结构定义的地方)。

如果您不喜欢在任何地方键入 struct (这在 C++ 中是不必要的),您可以 typedef 结构:

typedef struct no_start no_start;

no_start* insert_start(prog* program){
   no_start* data = malloc(sizeof(*data));
   data->node_program = program;
   return data;
}

当然,在 C++ 中您应该使用 new,而不是 malloc

关于c++ - 带有指针 : Member reference base type (. ..) 的函数不是结构或 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29683031/

相关文章:

c - 不显示链表中节点追加的结果

javascript - 如何将数据转换为这样的结构

c++ - 如何将 HEX 转换为 ASCII 字符串?

c++ - 在库中定义常量变量 pi

c++ - 使用编译器定义的宏连接

c++ - 我们可以存储 unordered_map<T>::iterator 吗?

c - 字符串的范围查询

java - 仅通过使 head = null 删除单个链表?

c++ - C++ 最危险的特性是什么?

c++ - 鲨鱼机器学习库 : undefined reference to `cblas_ddot'