为什么同一个变量打印不同的输出?

Han*_*hen 2 c pointers

#include <stdlib.h>
#include <stdio.h>
void roll_three(int* one, int* two, int* three)
{

  int x,y,z;
  x = rand()%6+1;
  y = rand()%6+1;
  z = rand()%6+1;

  one = &x;
  two = &y;
  three = &z;
  printf("%d %d %d\n", *one,*two,*three);  
}
int main()
{
  int seed;
  printf("Enter Seed: ");
  scanf("%d", &seed);
  srand(seed);
  int x,y,z;
  roll_three(&x,&y,&z);
  printf("pai: %d %d %d\n", x,y,z);
  if((x==y)&&(y==z))
    printf("%d %d %d Triple!\n",x,y,z);
  else if((x==y)||(y==z)||(x==z))
    printf("%d %d %d Double!\n",x,y,z);
  else
    printf("%d %d %d\n",x,y,z);
  return 0;

}
Run Code Online (Sandbox Code Playgroud)

这个终端,我为种子输入123.但是,roll_three中的printf和main中的printf给出了不同的输出?为什么*one和x不同?

Sch*_*ern 6

问题出在这里:

one = &x;
two = &y;
three = &z;
Run Code Online (Sandbox Code Playgroud)

因为one,twothree为指针,你已经改变了他们点什么,但现在他们不再指向mainx,yz.它与此类似......

void foo(int input) {
    input = 6;
}

int num = 10;
foo(num);
printf("%d\n", num);  // it will be 10, not 6.
Run Code Online (Sandbox Code Playgroud)

相反,您希望更改存储在它们指向的内存中的值.因此,取消引用它们并为它们分配新值.

*one = x;
*two = y;
*three = z;
Run Code Online (Sandbox Code Playgroud)

您甚至可以消除中间值.

*one   = rand()%6+1;
*two   = rand()%6+1;
*three = rand()%6+1;
Run Code Online (Sandbox Code Playgroud)