【问题标题】:Will the address pointed by pointer change if we change char* ptr = ;如果我们改变 char* ptr = ; 指针指向的地址会改变吗?
【发布时间】:2020-02-03 02:21:01
【问题描述】:
char* ptr = "hello";
ptr = "world";

ptr的地址会变吗?

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

案例一:

[更改前]

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";

【问题讨论】:

标签: c arrays pointers char ip-address


【解决方案1】:

指针会改变。文本“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

【讨论】:

  • 所以即使我们关闭编程软件,文本“你好”仍然保留在计算机内存中。它就在那里,永远不会自动消失,对吧?
  • @ChenerZhang 不,当您的程序干净退出时它会消失。
  • 请注意,您打印的“ptr 的地址”不是ptr 的地址——它是in ptr 的地址(ptr 的值)。令人困惑的单词选择。
【解决方案2】:

将指针从&amp;"hello"[0] 重新分配到&amp;"world"[0] 会明显改变它的值。 (&amp;[0] 只是使原本隐含的数组衰减显式)。

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

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

但是我安装的编译器(tcc、gcc、clang)都没有这样做。

对于

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

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

0x55c30f718004
0x55c30f718014
0x55c30f71800e

【讨论】:

    【解决方案3】:

    如果您只是直接使用指针,操作系统将在不同的位置为“hello”和“world”分配内存,您基本上会将指针更改为这些不同的地址。

    因此,在情况 2 中,“hello”、“world”和“something else”将有 3 个不同的位置,当您执行 ptr = “something else”时,指针只会重新分配到第三个位置

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

    【讨论】:

    • 不是那个操作系统。
    • @PaulOgilvie 还有谁执行程序?
    • @sleeping_dragon C 实现分配地址,操作系统只是将程序加载到内存中。
    猜你喜欢
    • 2016-05-26
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多