Question

I am writing a program to store multiple typedef "Item" instances in a queue (using this queue implementation) and I am running into a problem getting the data back from the queue.

Here is the relevant code, minus the file open/close lines (the code takes an input file and stores individual values into the instance):

Sample file:
1 2 10 20 30
------------
/* create new item */
Item *newItem = malloc(sizeof(Item));

/* string tokenizer */
...

/* set item variables */
newItem->value1 = strtol(tokens[0], NULL, 10);  //should contain 1
newItem->value2 = strtol(tokens[1], NULL, 10);  //should contain 2
newItem->value3 = strtol(tokens[2], NULL, 10);  //should contain 10
newItem->value4 = strtol(tokens[3], NULL, 10);  //should contain 20
newItem->value5 = strtol(tokens[4], NULL, 10);  //should contain 30

/* add to item queue */
queue_push_tail(itemQueue, &newItem);

/* add second item with different values, same method as above */
...

/* check queue values */
if(!queue_is_empty(itemQueue)) {
    Item *itemHead = queue_peek_head(itemQueue);        //this should differ...
    printf("Head: %d %d\n", itemHead->value1, itemHead->value5);
    Item *itemTail = queue_peek_tail(processQueue);     //...from this
    printf("Tail: %d %d\n", itemTail->value1, itemTail->value5);
}

How can I then access one of these items to view a variable? I thought I could use something like queue_peek_head(itemQueue)->value1 to see the first variable in the item (in the above example, 1 since that was stored in the first newItem.value1 in the queue), but that doesn't work for some reason.

Was it helpful?

Solution

Like @WhozCraig said in the previous comment, queue_peek_head() is supposed to return 'void *' which you should cast to 'Item *'.

Another issue with your code - 'newItem' is an on-stack variable, you can keep in a queue only as long as you are within the call stack of the function that pushed newItem to the queue. A safer practice would be to allocate newItem before pushing to a queue and free it somewhere else when you don't need it to be queued anymore.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top