[英]Pointer typecasting in c
I am writing an implementation of graphs in C language. 我正在用C语言编写图形的实现。 I came across a situation where I am not able to figure out the reason for the way the compiler is behaving with a pointer typecast warning.
我遇到了一种情况,我无法弄清编译器表现出指针类型转换警告的方式的原因。 Here are the structures;
这是结构;
#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];
I got a pointer typecast warning[enabled by default] when I do this kind of operation. 进行此类操作时,出现指针类型转换警告(默认情况下启用)。
I was not able to remove this warning even after trying to typecast with every possible cast. 即使尝试使用所有可能的演员表进行类型转换,我也无法删除此警告。
Finally I made a code change in the structure and suddenly the warning was gone. 最终,我对结构进行了代码更改,警告突然消失了。 The structure code change was this:-
结构代码更改是这样的:
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];
Now the warning is gone and code runs without any warnings. 现在警告消失了,代码运行时没有任何警告。
I do not understand why is this happening; 我不明白为什么会这样。 can anybody help me with this problem?
有人可以帮助我解决这个问题吗?
The problem is here: 问题在这里:
typedef struct {
int y;
int weight;
struct edgenode *next;
} edgenode;
It is not clear what type struct edgenode *next;
目前尚不清楚什么类型的
struct edgenode *next;
is referring to (it doesn't matter; somewhere, presumably, there's a struct edgenode
defined), but it is not this structure because it has no tag. 是指(没有关系;大概在某个地方定义了一个
struct edgenode
),但是它不是这种结构,因为它没有标签。 You need: 你需要:
typedef struct edgenode
{
int y;
int weight;
struct edgenode *next;
} edgenode;
Now the pointer refers to another structure of this same type. 现在,指针指向相同类型的另一个结构。 So, the fix you found was the correct fix for your problem.
因此,您找到的修复是针对您问题的正确修复。
Remember: a typedef
is an alias (alternative name) for an existing type. 记住:
typedef
是现有类型的别名(替代名称)。 You created a type name edgenode
, but you had not defined the type struct edgenode
. 您创建了一个类型名称
edgenode
,但尚未定义类型struct edgenode
。 You don't have to fully define a structure type before you create pointers to it; 在创建指向结构类型的指针之前,不必完全定义它。 this can be a good way of creating 'opaque types'.
这可能是创建“不透明类型”的好方法。
The other way to define things is: 定义事物的另一种方法是:
typedef struct edgenode edgenode;
struct edgenode
{
int y;
int weight;
edgenode *next;
};
This says that the type name edgenode
is an alias for a struct edgenode
; 这表示类型名称
edgenode
是struct edgenode
的别名; the structure definition then tells the compiler what a struct edgenode
looks like. 然后,结构定义告诉编译器
struct edgenode
外观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.