问题
i was trying to learn array implementation of a queue in the given code
#include <stdio.h>
main()
{
int q[10]={0}, i, front=-1, rear=-1, max=10, n, item;
printf("\n"
"\tMENU\n"
"1.ENQUEUE\n"
"2.DEQUEUE\n"
"3.DISPLAY\n"
"4.EXIT\n"
);
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
if(rear<max-1)
// .............so on
they have not asked user to input size of the queue but already defined it as 10.Is it only for this case or should we always define it and not give user any control over size of the queue?
PS:any good source for learning queue and its implementation in c for a beginner
回答1:
If you know the size of the queue in advance, this is the best method. Otherwise, you can ask the user to input the preferred size of the queue and dynamically allocate memory from the heap:
int queue_size;
printf("\nEnter queue size\n");
scanf("%d",&queue_size);
int *q = malloc(queue_size * sizeof(int));
回答2:
Is it only for this case or should we always define it and not give user any control over size of the queue?
No. You can take the size from user. Use variable length arrays and do not forget to compile your code in C99 mode (-std=c99).
int size;
scanf("%d", &size);
int q[size];
memset(q, 0, sizeof(q));
回答3:
The data structure book by Forozan and Gilberg is very good for beginners. Also you can use ppt from slideshare.com
来源:https://stackoverflow.com/questions/22433457/input-size-of-a-queue-by-the-user