I need a global structure, which defines an array of Queues. I want to use pointers for educational purposes. Inside a.h I defined the struct Queue:
typedef struct Queue
{
int size;
q_elem *root;
q_elem *last;
} Queue;
and the external variable
extern Queue **queue;
a.c has the function Queue* queue_new() to create a new queue.
now b.c uses the global variable Queue **queue; and I want to create an array of queues.
What I tried was:
queue = calloc(num_queues, sizeof(Queue*));
int i;
for(i=0; i < num_queues; i++){
queue[i] = queue_new();
}
But it doesn't seem to work correctly when I check inside my debugger. What am I doing wrong?
Queue* queue_new() {
Queue *newQ = (Queue*) malloc(sizeof(Queue));
if (newQ == NULL)
return NULL;
*newQ = (Queue) {0, NULL, NULL};
return newQ;
}
Not a solution, but too big for comments.
I see nothing wrong, I think your problem is elsewhere in code.
Just many questionable things about this as an FYI.
1.As @Rohan said, how is it not working?
2.
int size;
should besize_t size;
.3.OP has not shown
Queue **queue;
I assume there is aQueue **queue;
someplace. Being in static space, it will get initialized to 0. Better to explicitly initialize it toNULL
.4."... create an array of queues" is really " create an array of queues pointers".
5.Interesting you had a
NULL
check withmalloc()
, but not withqueue = calloc()
.6.
int i;
should besize_t i;
7.
Queue *newQ = (Queue*) malloc(sizeof(Queue));
: the cast(Queue*)
is not needed.8.Suggest
Queue *newQ = malloc(sizeof(*newQ));
instead.9.
Queue* queue_new()
should beQueue* queue_new(void)
.10.Where is
num_queues
defined and initialized?