gpt4 book ai didi

C 动态增加队列

转载 作者:行者123 更新时间:2023-11-30 20:27:28 25 4
gpt4 key购买 nike

我正在尝试创建一个队列,当它第一次达到 3 的大小时,它的大小会动态增加 3。我没有太多使用 malloc 或 realloc,但据我所知,它们在代码中应该是正确的

**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();
}
}

最佳答案

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

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

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

关于C 动态增加队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19490651/

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