为什么指针值会改变?

时间:2016-06-07 14:05:14

标签: c pointers

在玩和尝试理解指针的过程中,我找到了一些我无法解释的东西。我有几个指针示例和操作数据:

#include <stdio.h>

void test1(int** pp)
{
  int var = 1;
  *pp = &var;
}

void test2(int** pp)
{
  int var = 2;
  *pp = &var;
}

int *test3(int** pp) {
  int var = 3;
  *pp = &var;
  return *pp;
}

int test4(int** pp) {
  int var = 4;
  *pp = &var;
  return **pp;
}

int *test5(int* p) {
  int var = 5;
  *p = var;
  return p;
}

void test6(int* p) {
  int foo = 555;
}

int main()
{
  printf("WTF\n");
  int numbers = 1234;
  int *p1;
  p1 = &numbers;

  test1(&p1);
  printf("changes1: p1=%d\n", *p1);

  test2(&p1);
  printf("changes2: p1=%d\n", *p1);

  int *p2 = test3(&p1);
  printf("changes3: p1=%d\n", *p1);
  printf("changes: p2=%d\n", *p2);

  int p4 = test4(&p1);
  printf("changes4: p1=%d\n", *p1);
  printf("changes: p4=%d\n", p4);

  int *p5 = test5(p1);
  printf("changes5: p1=%d\n", *p1);
  printf("changes: p5=%d\n", *p5);

  test6(p1);
  printf("changes6: p1=%d\n", *p1);
  return 0;
}

以下输出为

  WTF
  changes1: p1=1
  changes2: p1=2
  changes3: p1=3
  changes: p2=3
  changes4: p1=4
  changes: p4=4
  changes5: p1=5
  changes: p5=5
  changes6: p1=555

为什么test6中p1的值是555?我不是在接触或改变它?

0 个答案:

没有答案
相关问题