我正在用 C 语言编写图形的实现。我遇到了一种情况,我无法弄清楚编译器处理指针类型转换警告的方式的原因。 这是结构;
#define MAXV 10
typedef struct {
int y;
int weight;
struct edgenode *next;
} edgenode;
typedef struct {
edgenode *edge[MAXV+1];
int degree[MAXV+1];
// other info of graph
} graph;
// operation in some other function
p->next = g->edge[x];
当我进行这种操作时,我得到了一个指针类型转换警告[默认启用]。
即使在尝试对所有可能的类型转换进行类型转换后,我也无法删除此警告。
最后我对结构进行了代码更改,突然警告消失了。
结构代码更改是这样的:-
typedef struct edgenode { // note that I have added structure name here
// same as above definition
} edgenode;
// operation in some other function
p->next = g->edge[x];
现在警告消失了,代码运行时没有任何警告。
我不明白为什么会发生这种情况;谁能帮我解决这个问题?
最佳答案
问题出在这里:
typedef struct {
int y;
int weight;
struct edgenode *next;
} edgenode;
不清楚 struct edgenode *next;
指的是什么类型(没关系;在某处,大概定义了一个 struct edgenode
),但是它不是这种结构,因为它没有标签。你需要:
typedef struct edgenode
{
int y;
int weight;
struct edgenode *next;
} edgenode;
现在指针指向同一类型的另一个结构。因此,您找到的修复是针对您的问题的正确修复。
记住:typedef
是现有类型的别名(替代名称)。您创建了类型名称 edgenode
,但尚未定义类型 struct edgenode
。在创建指向它的指针之前,您不必完全定义结构类型;这可能是创建“不透明类型”的好方法。
另一种定义事物的方式是:
typedef struct edgenode edgenode;
struct edgenode
{
int y;
int weight;
edgenode *next;
};
这表示类型名称 edgenode
是 struct edgenode
的别名;然后结构定义告诉编译器 struct edgenode
是什么样的。
关于c - c中的指针类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20167846/