简体   繁体   English

指向指针的指针,如何获取值?

[英]Pointer to a pointer, how do I get values?

Lets say I have the following code, 可以说我有以下代码,

typedef struct WordNode WordNode;
struct WordNode {
  int       freq;   // The frequency of the the word.
  char     *word;   // The word itself.
  WordNode *next;   // The next word node in the list.
};

struct WordSet {
  int       size;   // The number of elements in the set.
  WordNode *head;   // The starting node in the set.
};

After this, I've got some functions that initialize these structs. 在此之后,我得到了一些初始化这些结构的函数。 To prevent too much code in this post, I'm going to avoid posting those functions here. 为了防止在这篇文章中编写过多的代码,我将避免在此处发布这些功能。

Now, lets say I have the following, 现在,假设我有以下情况,

  WordNode **p = wset->head; // can't change this line

Here, p is basically a pointer pointing to a pointer, correct? 在这里,p基本上是指向指针的指针,对吗?

And then, if I do this: 然后,如果我这样做:

(*p) == NULL

This would return true if p is pointing to NULL, right? 如果p指向NULL,则返回true,对吗?

Now, how would I get the word stored in wset->head? 现在,如何将单词存储在wset-> head中?

Can I do this? 我可以这样做吗?

(*(*p))->word

And if I want p to point to the next WordNode, can I do this? 如果我想让p指向下一个WordNode,可以这样做吗?

p = (*(*p))->next

I just want to know if all this is valid syntax so that I know I'm using pointers correctly. 我只想知道所有这些是否都是有效的语法,以便知道我正确使用了指针。

Not really. 并不是的。 (*(*p))->word is a total dereferenciation. (*(*p))->word是总取消引号。 So it would either be (*(*p)).word or (*p)->word . 因此它可能是(*(*p)).word(*p)->word

You can imagine it that way, that the -> -Operator takes away one reference for you. 您可以这样想象-> -Operator为您删除一个参考。

obj->field is the same as (*obj).field obj->field(*obj).field

Just for the sake of simplicity, whenever I have to deal with double pointer and I need the value I all the time go via an intermediate variable 只是为了简单起见,每当我必须处理双指针并且需要随时通过中间变量访问值时,

eg 例如

WordNode **ptr2ptr = wset->head;
WordNode *ptr = *ptr2Ptr;
WordNode value = *ptr;

or to get the head: 或得到头:

WordNode head = ptr->head;

Now I'm just answering the question which is, how to access the value of a pointer to pointer. 现在,我只是在回答一个问题,即如何访问指向指针的指针的值。 You must be careful that your wset->head contains actually a pointer to pointer which is normally not the case in a linked list the way I understand you are trying to do. 您必须小心wset-> head实际上包含一个指向该指针的指针,在链表中,通常不是我所理解的那样。 This is also not the way you have defined your head member... 这也不是您定义负责人的方式...

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

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