#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不同?
问题出在这里:
one = &x;
two = &y;
three = &z;
Run Code Online (Sandbox Code Playgroud)
因为one,two和three为指针,你已经改变了他们点什么,但现在他们不再指向main的x,y和z.它与此类似......
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)