Odingod
Odingod

Reputation: 67

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.

Upvotes: 2

Views: 172

Answers (2)

Carey Gregory
Carey Gregory

Reputation: 6846

Ask yourself what type of object does ret->target point to and what type of object is it? Are they the same types of objects?

Upvotes: 2

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

Your typedef-definitions are mixed up badly. I'm surprised it even compiles.

You first defined typedef-name Edge as

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. (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.)

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. It is simply illegal in C.

Upvotes: 6

Related Questions