指针操作后如何获取指针指示的实际值?
How can I get real value which pointer indicate after pointer operation?
当我输入这样的代码时,我可以看到地址正常工作。
但在实际值中,我可以在指针操作后从该指针获取实际值。
旧值和新值的建议结果相同。
源码
#include <stdio.h>
int main()
{
float value;
float *pd;
printf("input float value : ");
scanf("%f", &value);
pd = &value;
printf("%d\n", pd);
printf("%f\n", *pd);
*(pd)++;
printf("%d\n", pd);
printf("%f\n", *pd);
return 0;
}
预期结果
当我将值设置为浮点值时,'value' 比如 12.345
input float value : 12.345
1539432628
12.345000
1539432632
12.345000
实际结果
input float value : 12.345
1539432628
12.345000
1539432632
109143502767521792.000000
你的期望是错误的。
pd = &value;
将value
的地址存入pd
访问 *pd
给出变量 value
内的值,即 12.345
现在使用 *(pd)++;
,你增加 pd
的地址,使其指向下一个位置,现在 pd
是 而不是 指向 value
并且行为未定义。
我添加的评论应该准确解释发生了什么。
#include <stdio.h>
int main()
{
float value;
float *pd;
printf("input float value : ");
scanf("%f", &value);
pd = &value; // pd points to the variable value
printf("%p\n", (void*)pd); // correct way to print pointer values
printf("%f\n", *pd); // print the value pointed by pd, in other words
// print value
pd++; // *(pd)++ is just a convoluted way to say pd++
printf("%d\n", pd); // print new pd pointer (which should be 4 higher)
printf("%f\n", *pd); // print value pointed by pd (which now no longer points to
// value but points 4 bytes further
printf("%f\n", *(pd - 1)); // should print the value because pd - 1 points
// to value
return 0;
}
如果你想知道为什么上面的代码是*(pd - 1)
而不是*(pd - 4)
,google c指针算法.
当我输入这样的代码时,我可以看到地址正常工作。
但在实际值中,我可以在指针操作后从该指针获取实际值。
旧值和新值的建议结果相同。
源码
#include <stdio.h>
int main()
{
float value;
float *pd;
printf("input float value : ");
scanf("%f", &value);
pd = &value;
printf("%d\n", pd);
printf("%f\n", *pd);
*(pd)++;
printf("%d\n", pd);
printf("%f\n", *pd);
return 0;
}
预期结果
当我将值设置为浮点值时,'value' 比如 12.345
input float value : 12.345
1539432628
12.345000
1539432632
12.345000
实际结果
input float value : 12.345
1539432628
12.345000
1539432632
109143502767521792.000000
你的期望是错误的。
pd = &value;
将value
的地址存入pd
访问 *pd
给出变量 value
内的值,即 12.345
现在使用 *(pd)++;
,你增加 pd
的地址,使其指向下一个位置,现在 pd
是 而不是 指向 value
并且行为未定义。
我添加的评论应该准确解释发生了什么。
#include <stdio.h>
int main()
{
float value;
float *pd;
printf("input float value : ");
scanf("%f", &value);
pd = &value; // pd points to the variable value
printf("%p\n", (void*)pd); // correct way to print pointer values
printf("%f\n", *pd); // print the value pointed by pd, in other words
// print value
pd++; // *(pd)++ is just a convoluted way to say pd++
printf("%d\n", pd); // print new pd pointer (which should be 4 higher)
printf("%f\n", *pd); // print value pointed by pd (which now no longer points to
// value but points 4 bytes further
printf("%f\n", *(pd - 1)); // should print the value because pd - 1 points
// to value
return 0;
}
如果你想知道为什么上面的代码是*(pd - 1)
而不是*(pd - 4)
,google c指针算法.