繁体   English   中英

c中的指针类型转换

[英]Pointer typecasting in c

我正在用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;
};

这表示类型名称edgenodestruct edgenode的别名; 然后,结构定义告诉编译器struct edgenode外观。

暂无
暂无

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

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