【发布时间】:2017-11-03 21:42:04
【问题描述】:
我有两个版本的代码。一个有效,另一个无效。
工作代码如下:
int main()
{
int i;
char str[] = "Hello World";
std::cout<<"The string value before memset is : "<<str<<std::endl;
memset (str,'-',6);
std::cout<<"The string value after memset is : "<<str<<std::endl;
return 0;
}
它给出了预期的输出:
The string value before memset is : Hello World
The string value after memset is : ------World
现在,我有另一个版本的代码,我想在其中使用 char 指针,但这段代码不起作用。我得到以下输出:
int main()
{
char *str;
str = "Hello World";
std::cout<<"The string value before memset is : "<<str<<std::endl;
memset (str,'-',6);
std::cout<<"The string value after memset is : "<<str<<std::endl;
return 0;
}
The string value before memset is : Hello World
Segmentation fault (core dumped)
我只是不知道发生了什么。你能帮我解决这个问题吗?
【问题讨论】:
-
“我有另一个版本的代码” - 给我们看看!
-
大声笑 - 你展示了有效的代码,而不是失败的代码!
-
我知道它在说什么 - 它说
char *str = "Hello World" -
字符串字面量是常量。您不能也不应该修改它们。这就是为什么在声明指向它们的指针时应该始终使用
const char*。 -
@enjal 那是因为你不应该修改数据!指针指向的文字字符串是 constant.
标签: c++ segmentation-fault memset