In C I try to learn queue data structure and make pointer to struct but inside the struct there is pointer to array. Here queue
is struct, q
is pointer to the struct, and inside struct there are rear
, front
, num
and int *que
(pointer to array to store data)
typedef struct {
int max;
int rear;
int front;
int num;
int *que;
} queue;
And malloc()
using
queue->que=malloc(sizeof(int)12) ; to make arrray And to access it,
q->que[q->rear++] //not to familiar,
First I'm not declaring array but can I access data pointed by que
using []
?
Is this mean access que[q->rear++]
inside q
pointer?
Is this the same as (q).que[q->rear++]
? I got segmentation fault .
Part of the code; but there are some errors
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int max;
int num;
int front;
int rear;
int *que;
} queue;
int initialization(queue*q, int max) {
q->num = 0;
q->front = 0;
q->rear = 0;
if (q->que =(int*)malloc(max * sizeof(int)) == NULL) { // got pointer NULL i dont know why
q->max = 0;
return-1;
}
q->max=max;
return 0;
}
int main() {
queue que;
if (initialization(&que, 12) == -1)
printf("fail");
else {
int m,x;
while (m != 0) {
printf("1.enque 2.deque. 3.peek 4.display 0. slese");
scanf("%d", &m);
switch (m) {
case 0: break;
case 1: printf("data");
scanf("%d", &x);
enqueue(&que, x);
break;
case 2: dequeue(&que, &x);
printf("%d is dequeue", x);
break;
case 3:x=peek(&que,&x);
printf("max now is %d", x);
break;
case 4:display(&que);
}
}
}
int enqueue(queue*q, int x) {
if (q->num >= q->max)
return -1;
else{
q->num++;
q->que[q->rear++]= x; //got segmentation fault
if (q->rear == q->max)
q->rear = 0;
}
}