C动态增加队列

时间:2013-10-21 09:24:41

标签: c memory dynamic queue realloc

当我第一次达到3的大小时,我正在尝试将队列的大小动态增加3。我没有使用过malloc或realloc那么多,但afaik它们在代码中应该是正确的

**Header:**
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

typedef char Titem;

/*The interface of queue  */
#define MAXN 3
typedef enum {NOT_OK, OK } Tboolean;
typedef struct {
         Titem array[MAXN];
         int number_of_items;
} Tqueue;
void initialize_queue (Tqueue *Pqueue);
Tboolean enqueue( Tqueue *p, Titem item);
Tboolean dequeue( Tqueue *p, Titem *Pitem);
void print_queue(const Tqueue *Pqueue);

**Queue functions:**
#include "jono.h"

void initialize_queue ( Tqueue *Pqueue)  {

    int size = 0;

    Pqueue->number_of_items = 0;
    *Pqueue->array = (Titem) calloc (MAXN, sizeof(MAXN));
    size = sizeof (Pqueue->array);
    printf ("%d\n", size);

}
Tboolean enqueue( Tqueue *Pqueue, Titem item) {

    int size = 0;

     if (Pqueue->number_of_items >= MAXN) {
        *Pqueue->array = (Titem) realloc (Pqueue->array, sizeof(Pqueue->array) + MAXN);
        size = sizeof (Pqueue->array);
        printf ("\%d", size);

        Pqueue->array[Pqueue->number_of_items++] = item;
        return(OK);
     }
     else {
        Pqueue->array[Pqueue->number_of_items++] = item;
        return (OK);
     }
}
Tboolean dequeue( Tqueue *Pqueue, Titem *Pitem) {
     int i;
     if (Pqueue->number_of_items == 0)
        return(NOT_OK);
     else {
        *Pitem = Pqueue->array[0];
        for (i = 0 ; i < Pqueue->number_of_items-1 ; i++)
            Pqueue->array[i] = Pqueue->array[i+1];
        Pqueue->number_of_items--;
        return (OK);
     }
}
void print_queue (const Tqueue *Pqueue) {
    int i;
    printf("\nQueue now: \n\n");
    for (i = 0 ; i <  Pqueue->number_of_items ; i++ ) {
         printf(" %c ", Pqueue->array[i]);
    }
    printf("\n\n");
}

**Main:** 
#include "jono.h"

int main(void) {
     Tqueue queue;
     Tboolean succeed;
     char chr;

     initialize_queue(&queue);
     printf("\nEnter a letter to be queued ");
     printf("\nor digit 1 to dequeue a letter");
     printf("\nor Return to quit a program\n");

     chr = _getche();
     while (chr != 10 && chr != 13) {
      if (isalpha(chr)) {
        succeed=enqueue(&queue, chr);
        print_queue(&queue);
        if (!succeed)
            printf("\n Enqueue operation failed\n");
      }
      if (chr == '1') {
        succeed = dequeue(&queue, &chr);
        if  (succeed) {
            printf("\na letter dequeued %c ", chr);
            print_queue(&queue);
            }
        else printf("\nDequeue operation failed\n ");
      }
      chr = _getche();
     }
}

1 个答案:

答案 0 :(得分:1)

typedef struct {
         Titem array[MAXN]; /* char array[3] */
         int number_of_items;
} Tqueue;

*Pqueue->array = (Titem) calloc (MAXN, sizeof(MAXN));

您不能为数组保留空间(只有指针可以使用(m/c/re)alloc