【发布时间】:2020-04-19 08:09:44
【问题描述】:
起初我正在创建这个程序来满足一个队列,并且一切正常。我目前正在尝试创建多个队列,方法是使用一个结构数组,每个队列都用自己的 ID 标识。但看起来它仍然只创建一个队列(当我使用一个列出所有队列的函数时,它只列出一个),我需要一些帮助来修复它。代码如下:
#define MAX_MESSAGES 5
#define MAX_MSG_LEN 20
#define MAX_QUEUES 5
typedef struct queue{
int front, rear, size;
char elements[MAX_MESSAGES][MAX_MSG_LEN];
}queue_t;
typedef struct MsgQs{
int id;
queue_t *qs[MAX_QUEUES];
}MsgQs_t;
int main(){
int id, i = 0;
MsgQs_t *qs = initializeMsgQs_t();
//MsgQs_t *qs = NULL;
queue_t *pq = NULL;
while(1){
printf("\n1) Create new queue");
printf("\n0) Quit");
printf("\nEnter choice:");
scanf(" %c", &choice);
getchar();
switch(choice){
case '1': //createQ
printf("\nCreating a queue!\nEnter Queue-ID (Ex. 1234):");
scanf("%d", &qs[i].id);
pq = createQ(qs[i].id);
printf("Queue with ID %d has been created successfully!\n", qs[i].id);
i++;
break;
case '0':
printf("\nQuitting");
exit(1);
default:
printf("Incorrect. Re-enter.\n");
break;
}
}
}
MsgQs_t* initializeMsgQs_t(){
MsgQs_t* qs = malloc(sizeof(MsgQs_t));
return qs;
}
queue_t* createQ(){
queue_t* pq = malloc (sizeof(queue_t));
pq -> front = 0;
pq -> rear = 0;
pq -> size = 0;
return pq;
}
尽管我最小化了程序以指示我在程序中遇到的第一个问题,但我还有更多关于这些多个队列的功能。
【问题讨论】:
-
您确定只创建 1 个吗?在
pq = createQ(qs[i].id);,看起来您正在创建许多,但每次迭代都用新的替换pq。 -
@Jason 我不是 100% 确定,我认为你是对的。我将如何修复它以不替换每次迭代?
标签: c arrays struct queue message-queue