检查相等指针和内存综述

Checking Equal Pointers & Memory Roundup

所以,我在 C:

中使用结构和指针实现队列

注意:我的程序使用 max_cells = 3。

这是我的 queue.h:

struct queue {
int max_cells; // Maximum number of cells in the queue
int cells_used; // Number of cells used
void **head; // Pointer to the head of queue
void **tail; // Pointer to the tail of queue
void **queue_base; // Pointer to the base of the queue
};

typedef struct queue Queue; // For convenience

这是我的入队代码:

/**
  * Enqueue a pointer into the queue
  * @param which_queue Pointer to Queue you want to push onto
  * @param ptr Pointer to be pushed
  * @return 1 if successful, 0 if not
  */
  int enqueue(Queue *which_queue, void *ptr) {

  // If the Queue is already full, print a message and terminate the function
  if ((which_queue->cells_used) == (which_queue->max_cells)) {
  printf("The queue is full. It can only contains %d cells.\n", which_queue->max_cells);
  return 0;
  }

  // Otherwise, enqueue the cell that head points to
  // Checking tail++ to see if it goes off the queue
  // If it does, then make tail point to the queue_base
  if (((which_queue->tail)++) == ((which_queue->queue_base) + (which_queue->max_cells))) {
  which_queue->tail = which_queue->queue_base;
  } else {
    // Push the pointer to the queue
    *(which_queue->tail) = ptr;
    // Point to the next free cell
    (which_queue->tail)++;
    // Then, increase the number of cells used in the Queue
    (which_queue->cells_used)++;
  }
  return 1; // Indicate success
  }

我通过打印出每个指向的内存位置来检查我的程序:(Foo 只是随机结构)

Enqueued new_foo1.
Current number of cells in the queue: 1
Head pointer is pointing to: 0x147d040
Tail pointer is pointing to: 0x147d050
Base pointer is pointing to: 0x147d040
Enqueued new_foo2.
Current number of cells in the queue: 2
Head pointer is pointing to: 0x147d040
Tail pointer is pointing to: 0x147d060
Enqueued new_foo3.
Current number of cells in the queue: 3
Head pointer is pointing to: 0x147d040
Tail pointer is pointing to: 0x147d070
The queue is full. It can only contains 3 cells.
-----------------------
Dequeued new_foo1
Current number of cells in the queue: 2
Head pointer is pointing to: 0x147d050
Tail pointer is pointing to: 0x147d070
Enqueued new_foo4
Current number of cells in the queue: 3
Head pointer is pointing to: 0x147d050
Tail pointer is pointing to: 0x147d080
*** (which_queue->queue_base) + (which_queue->max_cells) = 0x147d058 
Dequeued new_foo2
Current number of cells in the queue: 2
Head pointer is pointing to: 0x147d060
Tail pointer is pointing to: 0x147d080
Dequeued new_foo3
Current number of cells in the queue: 1
Head pointer is pointing to: 0x147d070
Tail pointer is pointing to: 0x147d080

问题出在标有***的行。为什么会这样?我认为内存位置应该是0x147d070.

请帮助我。谢谢

您还需要更明确地说明尾指针的确切作用——它指向添加到队列中的最后一个条目,还是指向添加最后一个条目之后的空闲 space排队?有些人喜欢用一种方式,有些人喜欢用另一种方式。

由于您首先递增尾指针,这意味着您希望尾指针指向最后添加的条目。但是正如 rpattiso 已经指出的那样,在使用它来将条目存储到队列中之后,你也不应该增加指针。

另一件事 -- 如果您以这种方式使用尾指针,请确保在向空队列添加内容时头指针设置正确。