1

我最近正在查看 Google 的C++ 材料,并遇到了以下用于演示指针的代码

void Unknown(int *p, int num);
void HardToFollow(int *p, int q, int *num);

void Unknown(int *p, int num) {
 int *q;

 q = #
 *p = *q + 2;
 num = 7;
}

void HardToFollow(int *p, int q, int *num) {
 *p = q + *num;
 *num = q;
 num = p;
 p = &q;
 Unknown(num, *p);
}

main() {
 int *q;
 int trouble[3];

 trouble[0] = 1;
 q = &trouble[1];
 *q = 2;
 trouble[2] = 3;

 HardToFollow(q, trouble[0], &trouble[2]);
 Unknown(&trouble[0], *q);

 cout << *q << " " << trouble[0] << " " << trouble[2];
}

我的问题如下: q 指针最初分配给了麻烦[1]。当发送到 HardToFollow 时,q 指针(现在称为 p)被更新为 4 的值,并且故障 [1] 随后也被更新。紧接着,原来的 q 指针(同样,在这个函数中称为 p)被重定向到指向一个局部变量(p = &q)。然而,到程序结束时,我们原来的 q 指针又回到了指向麻烦[1]。这怎么发生的?

4

3 回答 3

3

You can't simple modify main::q via passing it to HardToFollow function via pass by value. since your're passing q to it as pass by value, so in HardToFollow you can modify what's pointed by q via p and p itself but you can't modify q to point to something else.

slightly modifying the example shall do what you expecting it to :

void HardToFollow(int*& p, int q, int *num) {
 *p = q + *num;
 *num = q;
 num = p;
 p = &q;
 //Unknown(num, *p); //forget about this for now
}
于 2012-07-17T09:27:46.880 回答
1

I've added some comments that make it clear:

void HardToFollow(int *p, int q, int *num) {
  /* this modifies the value pointed to by p */
  *p = q + *num;
  *num = q;
  num = p;
  /* this does not modify the original pointer */
  p = &q;
  Unknown(num, *p);
}

[...]

  /* the memory address q points to is copied to the function scope */
  HardToFollow(q, trouble[0], &trouble[2]);
于 2012-07-17T09:04:47.533 回答
0

Because in function Unknown don't working with pointer q from the main function
The function works only with value of the pointer named num

于 2012-07-17T08:50:03.917 回答