结构指针之间的区别

Yog*_*esh 2 c c++

struct node
{
 int data;
 struct node *next;
};
Run Code Online (Sandbox Code Playgroud)

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

void traverse(struct node *q)
{ }
Run Code Online (Sandbox Code Playgroud)

void traverse(struct node **q)
{ }
Run Code Online (Sandbox Code Playgroud)

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

pb2*_*b2q 7

第一个参数列表传递指向a的指针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;
Run Code Online (Sandbox Code Playgroud)

第二个参数列表传递一个指针的指针到一个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:
Run Code Online (Sandbox Code Playgroud)

至于调用函数的两个版本,从main或以其他方式:给出一个指向你的结构的指针:struct node *arg;,

  • 你可以像这样调用第一个版本: traverse(arg);
  • 和第二个版本是这样的: traverse(&arg);

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

struct node arg;
struct node *ptrToArg = &arg;
Run Code Online (Sandbox Code Playgroud)

然后:

  • 你可以像这样调用第一个版本: traverse(&arg);
  • 和第二个版本是这样的: traverse(&ptrToArg);