Error: expression must have pointer-to-class type

Viewed 58

I am trying to implement queue using structs. Here is a struct itself:

struct Item
{
    datatype data;
    Item* next;
};

However, when I try to add a new element, I get an error:

void enqueue(Item** front, Item** rear, datatype D) { //add element to queue
    Item* temp;
    temp = new Item;
    temp->data = D;
    temp->next = NULL;
    if (*front == NULL){ // if queue is empty, make temp the first element
        *front = temp;
    }
    else { // else add it to the end
        rear->next = temp; //error is here
        *rear = temp;
    }
}

I've tried doing something like this (*rear)->next = temp; but then next is staying NULL.

Could you please help to fix this? Thanks.

1 Answers

If the queue is empty, you only assign front but rear must also point at the same Item.

if (*front == nullptr){ // if queue is empty, make temp the first element
    *front = temp;
}
else { // else add it to the end
    (*rear)->next = temp;         // <- fix like this
}
*rear = temp;                     // <- do this in both cases

Otherwise the next object you enqueue will be using a rear that is pointing at what you initialized it with at start, probably NULL.

Related