指针没有给出正确的价值

时间:2016-02-04 15:22:45

标签: c pointers

我正在为学校做一个项目,我正在努力学习如何使用指针。我试图让他们中继X,Y和Z的值。但是,我一直得到错误的值。 X应该等于1.Y应该等于2.Z应该等于3.

{
// Add the C statement(s) necessary to accomplish the task identified in the comments below


double A[3] = {2.718, 3.14, 2.718}; // declare an array A of 3 doubles

A[1] = 3.14;    // put the value 3.14 in the middle location of A

A[0] = 2.718;
A[2] = 2.718;   // put the value 2.718 in the first and last locations of A


printf("The first value of A is %f\n",A[0]);    // print the first value in A


printf("The last value of A is %f\n",A[2]); // print the last value in A


A[2] = A[0] + A[1]; // change the last value in A so that it is the sum of the first two and then print it


printf("The last value of A is %f\n", A[2]);
int B[4] = {10, 25, 50, 100};   // declare an array B of 4 integers with initial values 10, 25, 50, 100


int sum = B[0] + B[1] + B[2] + B[3];
printf("The sum of all four elements in B is %d\n",sum); // print the sum of all four elements in B


printf("Four elements in B in reverse order %d %d %d %d\n",B[3], B[2], B[1], B[0]); // print the four elements in B in reverse order (100, 50, 25, 10)


int X = 1;
int Y = 2;
int Z = 3;
printf("%d, %d, %d\n,",X,Y,Z);  // declare three integers, X Y and Z, assign them the values 1, 2 and 3 and print them


int *P1;    // declare three pointers to integers, P1, P2 and P3


int *P2;
int *P3;
P1 = &X;
P2 = &Y;    
P3 = &Z;    // point P1 to X, P2 to Y, and P3 to Z.


printf("%d, %d, %d\n",P1,P2,P3);    // print the values at X and Y and Z using the pointers P1 to P3
*P1 = 10;
printf("%d", P1);   // using P1 and not X, change the variable X's value from 1 to 10, then print it


return 0;
}

3 个答案:

答案 0 :(得分:1)

&XX的地址设置为P1。 但是,如果您想访问存储在该地址的值,那么您应该*P1

*P1的含义是什么?它表示存储在此地址的值。

P1=&X; //P1 takes address value of X;

如果您想在该地址打印值,那么

printf("Value of X %d\n",*P1);

答案 1 :(得分:0)

要访问指针指向的值,请写

printf("%d, %d, %d\n",*P1,*P2,*P3);
                      ^^^^^^^^^^^^

printf("%d", *P1);  
             ^^^^^

与你已经写过的方式相同

*P1 = 10;
^^^^^^^^

答案 2 :(得分:0)

指针是保存另一个变量地址的变量 指向int int *p的指针将保存int类型变量的地址 运算符&获取变量的地址,运算符*获取存储在地址中的值。
所以:

int x = 1;    //An integer i=1
int *p = &x;  // a pointer to int p to which we assign the address of x
//Now suppose x memory address is 100
printf("int=%d, pointer=%d\n", *p, p);  //Will print int=1, pointer=100

使用运算符p检索存储在*指向的地址处的值,并显示其值1,但如果您将指针变量p的内容放入其中得到100 但是您无法使用%d来打印指针,您必须使用%p
我只在printf中使用它来证明问题。