Global variables and struct arrays

188 views Asked by At

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;
}
2

There are 2 answers

0
chux - Reinstate Monica On

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 be size_t size;.

3.OP has not shown Queue **queue; I assume there is a Queue **queue; someplace. Being in static space, it will get initialized to 0. Better to explicitly initialize it to NULL.

4."... create an array of queues" is really " create an array of queues pointers".

5.Interesting you had a NULL check with malloc(), but not with queue = calloc().

6.int i; should be size_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 be Queue* queue_new(void).

10.Where is num_queues defined and initialized?

0
Armali On

What am I doing wrong?

The only thing you did wrong is how you interpreted your debugger's output.

When I check inside the debugger what **queue looks like, I only see one queue, not multiple.

You only see one queue because that's what **queue is, since queue is just a pointer to one pointer to a Queue (the type of queue is struct Queue **); queue's type doesn't convey the information that after the first one there are more Queue pointers, and so the debugger has no reason to print more.

If by chance your debugger is GDB, you could use a loop to print all queues:

(gdb) set $i = 0       
(gdb) while ($i < num_queues)   
 >p *queue[$i++]  
 >end

You could even define a command for that purpose:

(gdb) define pp
Type commands for definition of "pp".
End with a line saying just "end".
>set $i = 0       
>while ($i < $arg1)
 >p *$arg0[$i++] 
 >end           
>end           
(gdb) pp queue num_queues