const char*vs const char []

Ole*_*leg 14 c c++

据我所知,像"Hello"这样的字符串文字

被认为是char*在C和const char*C++中,对于这两种语言,字符串文字存储在只读存储器中.(如果我错了,请纠正我)

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Vla*_*cow 11

在此代码段中

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

  const char source2[] = "Hi"; //isn't "Hi" in the same memory region as "Hello" ?
  c2 = source2;
 }
Run Code Online (Sandbox Code Playgroud)

source2 是一个代码块的本地字符数组,它将在退出结束括号后的块时被销毁.

至于字符文字,它有静态存储持续时间.因此,退出代码块后,指向字符串文字的指针将有效.字符串文字将与字符数组相对.

考虑到在C中字符串文字的类型"Hello"char [6].这是任何字符串文字的类型是非const字符数组.不过你可能不会改变字符串文字.与C++中的C相反,字符文字具有const字符数组的类型.

  • @Oleg当您尝试访问尚未处于活动状态的对象时,程序行为未定义.简单地说,在最后一种情况下,早期为阵列分配的内存尚未被覆盖. (2认同)

For*_*veR 5

const char* source1 = "Hello";
Run Code Online (Sandbox Code Playgroud)

source1只是指向内存位置的指针,在那里Hello定义.

const char source2[] = "Hi";
Run Code Online (Sandbox Code Playgroud)

source2是字符数组类型的局部变量,并有另一个地址,即字符串文字Hi.在第一个}source2将被销毁c2并将被指向某个地方,但不是在位置上source2,所以它只是c2source2被销毁后取消引用的未定义行为.