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

时间:2016-02-26 22:33:36

标签: 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;

}

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

4 个答案:

答案 0 :(得分:6)

问题在于:

return

由于one = &x; two = &y; three = &z; onetwo是指针,您已经改变了他们指向的内容,但现在他们不再指向three的{​​{1 },mainx。它类似于......

y

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

z

您甚至可以消除中间值。

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

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

答案 1 :(得分:2)

roll_three中,您需要更改以下内容:

one = &x;
two = &y;
three = &z;

要:

*one = x;
*two = y;
*three = z;

第一个版本只是将它们指向局部变量。更正后的版本会更新调用者中的值。

答案 2 :(得分:1)

  

为什么* one和x不同?

one = &x;

应该是

*one = x;

您执行此操作的方式(one = &x)是错误的,因为您将指针one分配给在函数x之后不再存在的局部变量roll_three的地址。

你的功能应该是这样的:

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);  
}

答案 3 :(得分:0)

在roll_three函数中,

void roll_three(int* one, int* two, int* three)
{
  int x,y,z;
  x = rand()%6+1; // local variable x will have a value
  y = rand()%6+1;
  z = rand()%6+1;

  one = &x; // variable one is assigned with local variable x's address
            // so *one equals to x inside the function.
            // However, variable one supposed is the variable x's address in 
            // the main function, but now it is changed to the local x's address,
            // the main function variable x's value can't be updated as expected.
            // *one = x is the way you want to go.
  two = &y;
  three = &z;
  printf("%d %d %d\n", *one,*two,*three);  
}