-1

I am trying to create a queue by allocating memory to a pointer to a queue, yet I get this error when I write the name of the struct in the size slot. I really don't know how to explain this, so code:

structs, defined in queue.c:

struct queue {
    Node front;
    Node back;
    int num;
    int (*e_func)(Elem,Elem);
};
typedef struct node* Node;
struct node {
    Elem e;
    Node next;
    Node prev;
};

queue.h:

#ifndef QUEUE_H
#define QUEUE_H
#include <malloc.h>
#include <stdlib.h>
typedef struct queue* Queue;
typedef void* Elem;
Queue CreateQ(int (*equals)(Elem,Elem));
void Enqueue(Queue Q, Elem e);
Elem Dequeue();
Elem front(Queue Q);
Elem back(Queue Q);
int size(Queue Q);
int isIn(Queue Q, Elem e);
#endif

Usage of queue, in funcs.c:

Queue Q = (Queue)malloc(sizeof(struct queue));

The error is shown when mousing over the struct in the sizeof() argument. What the hell did I do wrong? I remember doing something similar in the past and it worked. I believe it might have something to do with the void pointer in node, but how do I solve this?

Sunspawn
  • 817
  • 1
  • 12
  • 27
  • Move `typedef struct node* Node;` above the definition of `struct queue`, perhaps? – user58697 Apr 22 '14 at 18:13
  • possible duplicate of [self referential struct definition?](http://stackoverflow.com/questions/588623/self-referential-struct-definition) – Deduplicator Apr 22 '14 at 18:19

1 Answers1

1

Define the typedef 'Node' first, so that it will be available for the next structure definition. However, now within the struct 'node', the 'next' and 'prev' elements cannot be of type 'Node' due to it being defined only after finishing the typedef. Nevertheless, 'struct node *' may be used to define 'next' and 'prev', due to 'struct node' is sufficiently defined.

typedef struct node {
    Elem e;
    struct node *next;
    struct node *prev;
    } *Node;

Later, you will find that you can reference 'next' and 'prev' just as though they had been defined as type 'Node'; since type 'Node' and type 'struct node *' (to the compiler) are equivalent.

struct queue {
    Node front;
    Node back;
    int num;
    int (*e_func)(Elem,Elem);
    };
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28
  • 1
    Posting code without an explanation, while it may solve the problem, is not very helpful. Could you add a brief description of what changes you made, and how they solve the issue? – ughoavgfhw Apr 22 '14 at 18:42