【问题标题】:C - Retrieving variable from item stored in queueC - 从存储在队列中的项目中检索变量
【发布时间】: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


【解决方案1】:

就像@WhozCraig 在之前的评论中所说,queue_peek_head() 应该返回“void *”,您应该将其转换为“Item *”。

您的代码的另一个问题 - 'newItem' 是一个堆栈变量,只有在将 newItem 推送到队列的函数的调用堆栈中,您才能保留在队列中。更安全的做法是在推送到队列之前分配 newItem,并在不再需要排队时将其释放到其他地方。

【讨论】:

  • 感谢您的回答!我现在正试图纠正你提到的第二点。当我创建两个Items 并将其排队时,似乎获得队列中的第一个项目(在头部)并没有给我创建的第一个Item。相反,它是第二个Item。这与您提出的问题有关吗? (编辑:我相信每次我读取一组新值时我都会以某种方式覆盖newItem。可以使用您的建议解决这个问题吗?有什么方法可以将通用Item 传递给队列吗?)跨度>
  • 您需要确保队列中的每个项目都有一个唯一的地址和一个良好健康的寿命:)。动态分配是要走的路。
猜你喜欢
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 2016-05-19
相关资源
最近更新 更多