bool EnQueue(Queue *pq, Item item) {
// 1. create a new node
Node *node;
if (QueueIsFull(pq))
return false;
else {
node = malloc(sizeof(Node));
if (node == NULL) {
fprintf(stderr, "Unable to allocate memory");
exit(EXIT_FAILURE);
}
}
// 2. Copy the item to the node, update next
node->item = item;
node->next = NULL;
// 3. update the rear of the queue (and front if first object)
pq->rear->next = node;
pq->rear = node;
pq->front = pq->front || NULL; // ***********************
// 4. update the queue size
pq->items++;
return true;
}
带星号的行给我以下警告:
q.c:49:15: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
pq->front = pq->front || NULL;
如果我删除 ||
,并将其设置为一个或另一个值,它可以正常工作而不会发出警告。为什么 ||
会发出警告?
答案 0 :(得分:1)
逻辑 OR 运算符 ||
如果两个参数都是 0(或 NULL),则结果为 0,否则为 1。因此,该语句所做的是将 pq->front
设置为整数值 0 或 1。
您说您希望结果是第一个非空值,类似于 or
在 Python 中的工作方式。如果是这种情况,该语句基本上不会执行任何操作,因为它只会将 pq->front
分配回自身(如果非空)或 NULL(如果它是 NULL)。
您可能正在寻找的是:
if (!pq->front) pq->front = node;
如果队列为空,这会将队列的前端设置为 node
。
在相关说明中,这是一个问题:
pq->rear->next = node;
如果 pq->rear
为 NULL。要解决这两个问题,请更改此设置:
pq->rear->next = node;
pq->rear = node;
pq->front = pq->front || NULL;
为此:
if (!pq->front) {
pq->front = node;
pq->rear = node;
} else {
pq->rear->next = node;
pq->rear = node;
}
这当然假设如果 pq->front
或 pq->rear
为 NULL,那么另一个也是 NULL。