1

I am trying to implement a queue using arrays, however my initialization function doesn't seem to work. Even the first line of the function is not executed. Here is the struct, function and main:

#include <stdio.h>
#include <stdlib.h>

typedef struct queue queue;

struct queue{
    int size, rear, front, length;
    int *arr;
};

queue* init(queue *queue1){
    queue1->size = 2;
    queue1->front = -1;
    queue1->rear = -1;
    queue1->length = 0;
    queue1->arr = (int*) malloc(sizeof(int)*queue1->size);
    return queue1;
}

int main(){
    queue* queue1 = init(queue1);
}

1 Answer 1

2

You must allocate space for your struct first.

Like this:

#include <stdio.h>
#include <stdlib.h>

typedef struct queue {
    int size, rear, front, length;
    int *arr;
} queue;

queue* init() {
    queue *queue1 = malloc(sizeof(queue));
    queue1->size = 2;
    queue1->front = -1;
    queue1->rear = -1;
    queue1->length = 0;
    queue1->arr = (int*) malloc(sizeof(int)*queue1->size);
    return queue1;
}

int main(){
    queue* queue1 = init();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.