Casting const char* to char* crashes
当我尝试将
1 2 3  | int myfunc(const char*); const char * str ="test"; myfunc( (char*)str ) // crash  | 
我怎样才能做到这一点?
您正在做的是未定义的行为。
您不允许更改
1  | char str[] ="test";  | 
这将为您创建字符串文字
更新资料
尝试修改字符串文字是未定义的行为。 如果我们看一下C ++标准草案的
Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.
崩溃是未定义行为的许多可能结果之一,也可能有一个看起来正常运行的程序。
或者,您可以创建一个自动数组,如下所示:
1  | char str[] ="test" ;  | 
其中将包含字符串文字的副本,您可以随后对其进行修改。
原版的
如果