gpt4 book ai didi

c++ - const char* 与 const char[]

转载 作者:太空狗 更新时间:2023-10-29 16:38:20 25 4
gpt4 key购买 nike

据我所知,一个像“Hello”这样的字符串

在 C 中被视为 char*,在 C++ 中被视为 const char*,对于这两种语言,字符串文字都以只读 内存。(如有错误请指正)

#include <stdio.h>

int main(void)
{
const char* c1;
const char* c2;

{
const char* source1 = "Hello";
c1 = source1;

const char source2[] = "Hi"; //isn't "Hi" in the same memory region as "Hello" ?
c2 = source2;
}

printf("c1 = %s\n", c1); // prints Hello
printf("c2 = %s\n", c2); // prints garbage

return 0;
}

为什么 source1source2 表现不同?(用 gcc -std=c11 -W -O3 编译)

最佳答案

在这段代码中

 {
const char* source1 = "Hello";
c1 = source1;

const char source2[] = "Hi"; //isn't "Hi" in the same memory region as "Hello" ?
c2 = source2;
}

source2 是代码块的局部字符数组,在退出右大括号之后的 block 后将被销毁。

至于字 rune 字,则它具有静态存储期限。因此,在退出代码块后,指向字符串文字的指针将有效。字符串文字将与字符数组相对。

考虑到在 C 中,字符串文字 "Hello" 的类型是 char [6]。也就是说,任何字符串文字的类型都是非常量字符数组。然而,您不能更改字符串文字。与 C 语言相反,C++ 中的字 rune 字具有 const 字符数组类型。

关于c++ - const char* 与 const char[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29008425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com