2015-02-21 3 views
0

Итак, я уверен, реализация очереди с использованием структуры и указателей в C:Проверка Равных Указатели и память Roundup

Примечания: Я использую 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.

Пожалуйста, помогите мне. Благодарю.

+0

Почему это должно быть '0x147d070'? и что, если это не так? –

+0

Я пытаюсь сделать очередь wrapparound. Итак, когда я деактивирую new_foo1, база очереди должна быть пустой. И я хочу переместить указатель на хвост, где находится база. Итак, я должен убедиться, что функция понимает, что если я увеличиваю указатель на хвост, он отключается от очереди. –

+0

вы увеличиваете хвост дважды в своем коде за один раз, один раз в if-условии и один раз в else, а когда if-condition истинно, 'ptr' никогда не добавляется. – ryanpattison

ответ

0

Вы также должны быть более ясными относительно того, что делает указатель на хвост - указывает ли он на последнюю добавленную в очередь запись или указывает на свободное пространство после последней записи, добавленной в очередь? Некоторым людям нравится делать это в одну сторону, а некоторым нравится делать это с другой.

Поскольку вы увеличиваете указатель на хвост, это означает, что вы хотите, чтобы указатель хвоста указывал на добавленную последнюю добавленную запись. Но, как уже указывал rpattiso, вы также не должны увеличивать указатель после его использования, чтобы сохранить запись в очереди.

Другое дело. Если вы используете указатель на хвост таким образом, убедитесь, что когда вы добавляете что-то в пустую очередь, чтобы указатель головы был установлен правильно.

Смежные вопросы