c - 使用指针算术困惑

标签 c pointers

我对使用指针算术有点困惑。我在代码中以注释的形式提出令人困惑的问题。我认为当它增加时,其他的也必须增加。有人可以解释一下吗?

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

最佳答案

tempstr 都是不同的指针变量。修改其中任何一个都不会导致其他的修改,但修改它们指向的数据才会生效。

您应该记住,在您的情况下,您可以修改 strtemp 但无法修改它们指向的字符串文字,因为字符串文字不可修改。

另请注意,对于指针数据类型 %pprintf 中用作格式说明符来打印它们指向的地址。

关于c - 使用指针算术困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33942901/

相关文章:

c++ - 删除 ptr C++ 后会发生什么

我可以在不使用堆的情况下编写 C 应用程序吗?

c - abs 没有分支,为什么这段代码有效

objective-c - 在 Objective C 中使用指针的最大优势是什么

c - 为什么readlines函数要使用alloc?

pointers - 如何使用interface{}将整数作为指针传递给函数

c - ARM Cortex A9 双核(Linux 或 VxWorks)上的多线程

C - malloc 大小小于参数大小的 strcpy

c++ - 如何使用指针 C++ 将二维数组中的元素复制到一维数组中

const char const *char[] 编译器警告