Home > Net >  Why is this code not working? The code should print the elements but it just runs and then exits wit
Why is this code not working? The code should print the elements but it just runs and then exits wit

Time:11-13

#include <stdio.h>
#include <stdlib.h>
struct queue
{
    int front;
    int rear;
    int size;
    int *arr;
};

void enqueue(struct queue *q, int value)
{
    if(q->rear!=q->size-1)
    {
        printf("Entry\n");

        q->rear  ;
        q->arr[q->rear] = value;
    }
}


int main()
{
    struct queue *q;   /*struct queue *q=(struct queue *)malloc(sizeof(struct queue));*/
    q->front = -1;
    q->rear = -1;
    q->size = 10;
    q->arr = (int *)malloc((q->size) * sizeof(int));

    enqueue(q,14);
    enqueue(q,7);
    enqueue(q,5);
    enqueue(q,4);
    enqueue(q,3);
    enqueue(q,2);
   
    for(int i=0;i<q->rear;i  ){
        printf("%d ",q->arr[i]);
    }
    return 0;
}

I was expecting the elements of the queue to be printed. When the line "struct queue *q;" is replaced with this " *struct queue *q=(struct queue *)malloc(sizeof(struct queue));" it works, what is the reason?

CodePudding user response:

The segmentation-fault occurs because you have not allocated memory for q.
What you have written as:

struct queue *q;

Is a pointer, that is, a variable that stores the memory address of another variable. You have created something that can point to memory but have not provided it any memory to point to.

malloc provides you memory from the heap, which is a typical way of having memory allocated and is why the commented code works.

An alternative would be to use memory on the stack:

struct queue q;
q.front = -1;
q.rear = -1;
q.size = 10;
q.arr = (int *)malloc((q.size) * sizeof(int));

And then using it as:

enqueue(&q,14);

CodePudding user response:

struct queue *q;
q = (struct queue *)malloc(sizeof(struct queue));  /*In order to write data, you first need to allocated to memory for it. and if you do it like q->arr you will allocated to memory for the second step so (think of this list as an array if you do q->arr you will allocated for arr[1] instead of arr[0])*/ 
q->front = -1;
q->rear = -1;
q->size = 10;

/but this will only allocate the first part in memory (only for arr[0])/ /*so you can write code in void enqueue(struct queue *q, int value) to allocated a new memory in each operation */ /I understand that you are trying to determine the memory in one go by assigning size to 10 , but you can not do like this.because the part you allocate here is just a value you put in arr[0], you can't use it as the size of your list./

  • Related