我正在编写一个程序来在队列中存储多个typedef
“Item”实例(使用this queue implementation),而且我遇到了从队列中恢复数据的问题。
以下是相关代码,减去文件打开/关闭行(代码接受输入文件并将单个值存储到实例中):
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);
}
如何访问其中一个项目以查看变量?我以为我可以使用queue_peek_head(itemQueue)->value1
之类的东西来查看项目中的第一个变量(在上面的示例中,1
,因为它存储在队列中的第一个newItem.value1
中),但是由于某种原因不起作用。
答案 0 :(得分:1)
就像@WhozCraig在上一条评论中所说的那样,queue_peek_head()应该返回'void *',您应该将其转换为'Item *'。
您的代码的另一个问题 - 'newItem'是一个堆栈上的变量,只要您在将newItem推送到队列的函数的调用堆栈中,您就可以保留在队列中。更安全的做法是在推送到队列之前分配newItem,并在不再需要排队时将其释放到其他地方。