首页 > 解决方案 > 如果我们改变 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";

标签: carrayspointerscharip-address

解决方案


指针会改变。文本“hello”保留在内存中,但不再以有效方式访问。

#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

推荐阅读