gpt4 book ai didi

c++ - 错误:表达式必须具有指向类的指针

转载 作者:行者123 更新时间:2023-12-01 14:53:20 24 4
gpt4 key购买 nike

我正在尝试使用结构实现队列。这是一个结构本身:

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

但是,当我尝试添加新元素时,出现错误:
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;
}
}

我尝试做类似 (*rear)->next = temp;的操作,但是接下来是保持NULL。

您能帮忙解决这个问题吗?谢谢。

最佳答案

如果队列为空,则仅分配front,但rear也必须指向相同的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

否则,您的 enqueue的下一个对象将使用 rear,它指向您在一开始对其进行初始化的对象,可能是 NULL

关于c++ - 错误:表达式必须具有指向类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60696748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com