zou*_*oul 4 c++ string initialization
我有以下代码:
#include <iostream>
using namespace std;
int main()
{
char* a = "foo";
char* b = "bar";
a = b;
cout << a << ", " << b << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这编译和工作,即.打印bar, bar.现在我想证明这里发生的事情不是复制字符串.我想改变b并表明a也有变化.我想出了这个简单的代码:
#include <iostream>
using namespace std;
int main()
{
char* a = "foo";
char* b = "bar";
a = b;
b[1] = 'u'; // ? just this line added
cout << a << ", " << b << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
......但它是段错误的.为什么?有趣的是,以下修改运行得很好:
#include <iostream>
using namespace std;
int main()
{
char* a = "foo";
char b[] = "bar"; // ? declaration changed here
a = b;
b[1] = 'u';
cout << a << ", " << b << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么它不像前一个那样段错?我想我错过了指针式和数组式字符串初始化之间的一些重要区别.
小智 6
当你写这个:
char *b = "bar";
Run Code Online (Sandbox Code Playgroud)
编译器分配一个匿名(无名)内存区域来存储字符串文字"bar".字符串文字可能不会被修改,因此编译器(在链接器和操作系统的帮助下)将字符串文字放在正在运行的程序的写保护内存空间的一部分中.当您尝试修改它时,操作系统会捕获它并导致程序出现分段错误.
(你的代码是C++,而不是C,但这与这个问题无关.)