【发布时间】:2014-03-02 06:39:37
【问题描述】:
我正在编写一个程序来将多个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 中),但这对某些人不起作用原因。
【问题讨论】:
-
这不是 C++。你没有得到类型化的指针。根据您使用的 API,
QueueValue(推送的值和通过剥离返回的值)是void *的同义词。在取消引用基础字段之前,您必须将其转换回Item*(并且您最好在执行此操作时拥有一个有效的Item地址)。 -
啊,我明白了。我一定把语法弄糊涂了。因此,当我尝试取回数据时,我应该在对
queue_peek_head的调用前加上(Item *)?取消引用基础字段到底是什么意思?抱歉,我还在掌握指针和参考资料。 -
if (!queue_is_empty(itemQueue)) { Item *p = queue_peek_head(itemQueue); do something with p }这是 C。忘记引用。思考指针。 -
完美,成功了!现在来解决我的代码中的其他问题。
标签: c pointers reference queue typedef