结构指针之间的区别

时间:2012-08-08 19:07:55

标签: c++ c

struct node
{
 int data;
 struct node *next;
};

以下两个功能有什么区别:

void traverse(struct node *q)
{ }

void traverse(struct node **q)
{ }

如何从主程序中调用上述函数?

3 个答案:

答案 0 :(得分:7)

第一个参数列表传递指向struct node的指针。这允许您更改函数体中的struct node。例如:

// this will change the structure, caller will see the changes:
q->data = newValue;

// but this will only change q in the function, caller WON'T see the NULL:
q = NULL;

第二个参数列表将指向的指针传递给struct node。这使您不仅可以更改函数体中的struct node,还可以更改指向的指针。例如:

// this will change the structure, caller will see the changes:
(*q)->data = newValue;

// This will change the pointer, caller will now see a NULL:
*q = NULL:

至于调用函数的两个版本,来自main或其他:给出指向结构的指针:struct node *arg;

  • 您可以调用第一个版本:traverse(arg);
  • 和第二个版本:traverse(&arg);

或者,给定一个声明为struct node arg;的结构,你可以指向它:

struct node arg;
struct node *ptrToArg = &arg;

然后:

  • 您可以调用第一个版本:traverse(&arg);
  • 和第二个版本:traverse(&ptrToArg);

答案 1 :(得分:4)

void traverse(struct node *q)
{ }

采用指向结构的指针。你可以这样称呼它:

struct node A;
traverse(&A);

此功能

void traverse(struct node **q)
{ }

获取指向结构的指针。你可以这样称呼它:

struct node A;
struct node* Aptr = &A;
traverse(&Aptr);

如果要修改传递给函数的原始变量,传递指针很有用,例如,如果你有这样的函数:

void setToNull(struct node ** q){
   *q = NULL;
}

然后你可以这样做:

struct node A;
struct node* Aptr = &A;
setToNull(&Aptr);
// Aptr is now equal to NULL.

答案 2 :(得分:2)

 void traverse(struct node *q)

只需将指针传递给函数。

 void traverse(struct node **q)

将指针传递给指针,以便更改原始指针。这是C ++通过引用传递指针的C等价物。在C ++中,您可以这样做:

 void traverse(node *& q)

你称之为:

 struct node* q;

 //...
 traverse(q); //calls first version
 traverse(&q);//calls second version