简体   繁体   English

C:结构中的结构

[英]C: structs in structs

My assignment is to create a simple graph that has both Nodes and Edges. 我的任务是创建一个包含节点和边缘的简单图形。 In my header file which was given and cant't be modified I have 在我给出的头文件中,我无法修改

typedef struct Edge_s* Edge;
typedef struct Node_s* Node;
typedef struct Graph_s* Graph;

and in my graph.c 在我的图表中

typedef struct{
  size_t w;
  struct Node_s* target;
}*Edge;

typedef struct{
  size_t value;
  Edge* edges;
  size_t s;
}*Node;

typedef struct{
  Node* nodes;
  size_t n;
  Edge* edges;
  size_t e;
}*Graph;

Edge create_edge(Node t, size_t w){
  Edge ret = malloc(sizeof(*ret));
  ret->target = t;
  ret->w = w;
  return ret;
}

This gives a warning on compile 这会在编译时发出警告

warning: assignment from incompatible pointer type

I'm kind of confused here, what am I getting wrong and how should I fix it? 我在这里有点困惑,我出错了什么,我该如何解决? The program is almost working and I'm getting one strange bug that I believe might be because of this. 该程序几乎正在工作,我得到一个奇怪的错误,我认为可能是因为这个。

Your typedef-definitions are mixed up badly. 你的typedef定义很糟糕。 I'm surprised it even compiles. 我很惊讶它甚至编译。

You first defined typedef-name Edge as 您首先将typedef-name Edge定义为

typedef struct Edge_s* Edge;

and then later re-defined it as 然后重新定义为

typedef struct{
  size_t w;
  struct Node_s* target;
}*Edge;

These two definitions define Edge in two completely unrelated ways. 这两个定义以两种完全不相关的方式定义Edge (All C compilers I know would immediately report an error if the first group of declarations would meet the the second group in the same translation unit.) (如果第一组声明符合同一翻译单元中的第二组,我知道的所有C编译器都会立即报告错误。)

I'd say that your second struct definition should be simply 我要说你的第二个结构定义应该是简单的

struct Edge_s {
  size_t w;
  struct Node_s* target;
};

Don't attempt to redefine an existing typedef-name. 不要尝试重新定义现有的typedef-name。 It is simply illegal in C. 在C中它完全是非法的

Ask yourself what type of object does ret->target point to and what type of object is it? 问问自己ret-> target指向哪种类型的对象以及它是什么类型的对象? Are they the same types of objects? 它们是相同类型的物体吗?

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

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