字符串赋值给指针与数组的区别

来源:互联网 发布:php程序员要求 编辑:程序博客网 时间:2024/06/05 02:11

代码

int Test() {    //  Test1    char str1[] = "hello world";    char str2[] = "hello world";    if (str1 == str2) cout << "str1 equal str2" << endl;    else cout << "str1 is not equal to str2" << endl;    char *pstr1 = "hello world";    char *pstr2 = "hello world";    if (pstr1 == pstr2) cout << "pstr1 equal to pstr2" << endl;    else cout << "pstr1 is not equal to str2" << endl;    //  Test2    char str3[12];    str3 = "hello world"; //error    char *pstr3;    pstr3 = "hello world";    return 0;}

Test1结果:

str1 is not equal to str2
pstr1 equal pstr2

分析 :

在C++中,常量字符串存储于一块特殊的存储区且仅有一份拷贝,当为pstr1和pstr2赋值相同的字符串常量时候,他们实际上指向相同的内存地址。

但用常量初始化数组,情况有所不同。对于数组初始化来说,字符串常量相当于构造函数中的初始化列表,当初始化数组时,会为数组分配相应长度的空间,并把字符串常量复制到数组中去。str1和str2的初始地址不同,因此它们的值也是不同的。

两者类似浅拷贝与深拷贝。

Test2结果:

为str3赋值时候会报错,pstr3却不会。

分析:

因为str3是数组名,是指针常量,不能修改。
pstr3是普通指针,赋值时,指向内存中的字符串常量的地址。

原创粉丝点击