I am pretty new to the coding but there is some problem i am experiencing with all my compilers and IDEs. Whenever i try to compile my c code in vs code or code blocks it does not give proper or to be specific desired output which i get perfectly when i use the same code on online compilers. for example,`the below code prints Hello and exits in VS Code but in online compiler it executes exactly the same way it should. I dont know if its a compiler problem or an IDE thing but if anybody knows this, please answer. I only encounter this with c language codes, in c it works fine.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int info;
struct node *next;
} node;
typedef struct
{
node *front;
node *rear;
} queue;
void
createqueue (queue * q)
{
q->front = q->rear = NULL;
}
int
isempty (queue * q)
{
if (q->front == NULL)
return 1;
return 0;
}
void
enqueue (queue * q, int val)
{
node *p = (node *) malloc (sizeof (node));
p->info = val;
p->next = NULL;
if (isempty (q))
q->front = q->rear = p;
else
{
q->rear->next = p;
q->rear = p;
}
}
int
dequeue (queue * q)
{
int t;
t = (q->front)->info;
node *p = (node *) malloc (sizeof (node));
p = q->front;
if (q->front == q->rear)
q->front = q->rear = NULL;
else
q->front = (q->front)->next;
free (p);
return t;
}
int
queuefront (queue * q)
{
int t;
t = q->front->info;
return t;
}
void
traverse (queue * q)
{
node *p = (node *) malloc (sizeof (node));
printf ("\n Queue is: ");
p = q->front;
while (p != NULL)
{
printf ("=>%d ", p->info);
p = p->next;
}
}
int
main ()
{
int choice, info, d, val;
queue *q;
printf ("hello\n");
createqueue (q);
do
{
printf ("\n MENU \n");
printf ("\n 1.ENQUEUE \n");
printf ("\n 2.DEQUEUE \n");
printf ("\n 3.FRONT \n");
printf ("\n 4.TRAVERSE \n");
printf ("\n 5.EXIT \n");
printf ("\n ENTER YOUR CHOICE: ");
scanf ("%d", &choice);
switch (choice)
{
case 1:
printf ("enter the value");
scanf ("%d", &val);
enqueue (q, val);
break;
case 2:
if (isempty (q))
{
printf ("Queue is empty");
break;
}
info = dequeue (q);
printf ("%d ", info);
break;
case 3:
if (isempty (q))
{
printf ("Queue is empty");
break;
}
d = queuefront (q);
printf ("front= %d \n", d);
break;
case 4:
if (isempty (q))
{
printf ("Queue is empty");
break;
}
traverse (q);
break;
case 5:
exit (0);
break;
}
}
while (choice > 0 && choice < 5);
return 0;
}
`
CodePudding user response:
queue *q; // uninitialized pointer
createqueue (q); // function tries to dereference it.
You must make q
point somewhere.
You should also learn how to use your IDE to debug -- the debugger would tell you immediately why your program exits (actually it doesn't exit, it crashes).