如果我们改变 char* ptr = ; 指针指向的地址会改变吗?

Will the address pointed by pointer change if we change char* ptr = ;

char* ptr = "hello";
ptr = "world";

ptr 的地址会改变吗?

如果我最初设置ptr = "hello",那么我设置ptr = "world""hello"去哪儿了,就这么消失了?

案例 1:

[变更前]

ptr = [h][e][l][l][o]; // address of ptr = 10001;

[变更后]

ptr = [w][o][r][l][d]; // address of ptr still = 10001;

案例 2:

[变更前]

ptr = [h][e][l][l][o]; // address of ptr = 10001;

[变更后]

ptr = [w][o][r][l][d]; // address of ptr still = 10002;
char* ptr = "hello";
ptr = "world";
// maybe 2 minutes later, i change again
ptr = "something else";

如果您只是直接使用指针,OS 将在不同的位置为 "hello" 和 "world" 分配内存,您实际上会将指针更改为那些不同的地址。

所以在情况 2 中,"hello"、"world" 和 "something else" 将有 3 个不同的位置,当您执行 ptr = [ 时,指针将被重新分配到第三个位置=21=]

另见:Why can a string be assigned to a char* pointer, but not to a char[] array?

指针会改变。文本 "hello" 仍为 in memory,但无法再以有效方式访问。

#include <stdio.h>

int main(void)
{
    const char* ptr = "hello";
    printf("The value of ptr is %p\n", ptr);
    ptr = "world";
    printf("The value of ptr is %p\n", ptr);
}

The address of ptr is 0000000000404000
The address of ptr is 0000000000404020

将指针从 &"hello"[0] 重新分配给 &"world"[0] 将明显改变其值。 ( &[0] 只是使隐式数组衰减显式)。

字符串文字保存在只读静态内存中(=它们具有程序的生命周期),并且 "hello""world" 考虑到它们的不同内容,绝对不能占据相同的位置。

将指针从 "hello" 更改为 "hello[=18=]world" 可能会使指针值保持不变,因为编译器可能会将两个字符串文字合并为一个 (6.4.5p7)。

但是 none 我安装的编译器(tcc、gcc、clang)正在执行此操作。

为了

#include <stdio.h>
int main()
{
    char *p;
    p = "hello";
    printf("%p\n", p);
    p = "hello[=10=]world";
    printf("%p\n", p);
    p = "world";
    printf("%p\n", p);
}

我得到不同的指针值,例如:

0x55c30f718004
0x55c30f718014
0x55c30f71800e