我对使用指针算术有点困惑。我在代码中以注释的形式提出令人困惑的问题。我认为当它增加时,其他的也必须增加。有人可以解释一下吗?
#include <stdio.h>
int main()
{
const char *str = "abcde";
const char *temp = str; // str is pointer to address of first element of temp isn't it?
printf("%d\n", temp - str); // zero okey
printf("temp str\n");
printf("%d %d\n", temp, str); // shows same adresses
str++; // hard to understand a point is here
printf("%d %d\n", temp, str); // why weren't also temp increased?
temp++;
printf("%d %d\n", temp, str); // why weren't also str increased?
temp++;
printf("%d %d\n", temp, str); // why weren't also str increased?
return 0;
}
最佳答案
temp
和 str
都是不同的指针变量。修改其中任何一个都不会导致其他的修改,但修改它们指向的数据才会生效。
您应该记住,在您的情况下,您可以修改 str
和 temp
但无法修改它们指向的字符串文字,因为字符串文字不可修改。
另请注意,对于指针数据类型 %p
在 printf
中用作格式说明符来打印它们指向的地址。
关于c - 使用指针算术困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33942901/