Jack
Jack

Reputation: 54

Queue implementation throws incompatible pointer type error

I think I'm missing general concepts on structs and pointers. Hence, below code is producing 2 warnings/errors and I don't understand why.

  1. Why is "queue->head = temp" producing following warning: warning: assignment from incompatible pointer type [enabled by default]

  2. Why is "queue->tail->next = temp" producing following error: error: dereferencing pointer to incomplete type.

Note: The line "Node *temp = newNode(data)" does not throw any error/warnings so it's successful.

typedef struct {
  int data;
  struct Node *next;
} Node;

typedef struct {
  struct Node *head;
  struct Node *tail;
} Queue;

void enQueue(Queue *queue, int data) 
{ 
    // Create a new node
    Node *temp = newNode(data); 


    // If queue is empty, then new node is both head and tail 
    if (queue->tail == NULL) 
    { 
       queue->head = temp;
       queue->tail = temp; 
       return; 
    } 

    // Add the new node at the end of queue and change tail 
    queue->tail->next = temp; 
    queue->tail = temp;
}

Upvotes: 1

Views: 412

Answers (1)

Matthias
Matthias

Reputation: 71

How did you get this code to compile? Your Node structure contains a pointer to another Node. In the way you declared your structure, the compiler does not know Node while parsing your structure definition. Hence, you must write:

1 typedef struct Node{
2   int data;
3   struct Node *next;
4 } Node;

In this way, the compiler knows how to handle your structure when parsing it. In line 3 it already knows that Nodeis structure. Since some of your code is missing, I created a minimal example that implements a super simple queue:

#include <stdlib.h>
#include <stdio.h>


#define MAX 5
typedef struct Node{
  int data;
  struct Node *next;
} Node;

typedef struct {
  struct Node *head;
  struct Node *tail;
} Queue;

Node* newNode(const int nodeData){
    Node* tmp = malloc(sizeof(*tmp));
    if (NULL == tmp){
        printf("Could not allocate Node ... exiting");
        exit(EXIT_FAILURE);
    }
    tmp->data = nodeData;
    tmp->next = NULL;
    return tmp;


}
void enQueue(Queue *queue, int data) 
{ 
    // Create a new node
    Node *temp = newNode(data); 


    // If queue is empty, then new node is both head and tail 
    if (queue->tail == NULL) 
    { 
        printf("Queue is empty\n");
       queue->head = temp;
       queue->tail = temp; 
       return; 
    } 

    // Add the new node at the end of queue and change tail 
    queue->tail->next = temp; 
    queue->tail = temp;
}

void printQueue(Queue* q){
    Node* tmp = q->head;
    while (tmp != NULL){
        printf("Value: %d\n", tmp->data);
        tmp = tmp->next;
    }
}

int main(void){
    Queue q;
    q.head = q.tail = NULL;
    int i;

    for (i = 0; i < MAX; ++i){
        printf("%d is entered into the queue\n", i);
        enQueue(&q, i);
    }
    printQueue(&q);
}

Upvotes: 1

Related Questions