简体   繁体   English

无效*指向清单中的无效*

[英]void * pointing to void * in a list

I have a list like so: 我有一个像这样的清单:

void * head = [void * a] --> [void * b] --> [void * b] --> NULL

Given void * head , how can I iterate through the list? 给定void * head ,我如何遍历列表?

Each void * points to another void * , with the final item in the list pointing to NULL . 每个void *指向另一个void * ,列表中的最后一项指向NULL

I think I need to use void ** , but I'm not completely sure. 我认为我需要使用void ** ,但我不确定。 Each item in the list is not in contiguous memory. 列表中的每个项目都不在连续内存中。

I have a list like this [...] 我有这样的清单[...]

This is not exactly a list - it is a multi-level pointer with the level unknown at compile time. 这不完全是一个列表-它是一个多级指针,在编译时级别未知。

I think I need to use void ** , but I'm not completely sure 我想我需要使用void ** ,但我不确定

Yes, you are right! 是的,你是对的! You can dereference the pointer one level at a time. 您可以一次取消引用指针的一级。

Here is what you can do: 您可以执行以下操作:

  • Set up a while loop that ends when head is NULL 设置while循环,当headNULL时结束
  • Inside the loop, make a void **next , and assign head to it 在循环内部,使void **next并为其分配head
  • Now dereference next, and assign the result to head , like this: head = *next 现在取消引用 ,然后将结果分配给head ,如下所示: head = *next
  • Continue with the loop until head is NULL . 继续循环,直到headNULL

Each iteration of the loop removes another level of indirection, until the final pointer is reached. 循环的每次迭代都会删除另一个间接级别,直到到达最终指针为止。

void *node = head;
while(node) {
    // do stuff with the node
    node = *((void**)node);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM