本文介绍了为什么字符*导致未定义的行为而的char []不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图修改字符串的原因未定义的行为:
Attempting to modify a string literal causes undefined behavior:
char * p = "wikipedia";
p[0] = 'W'; // undefined behaviour
要prevent一种方法是把它定义为一个数组,而不是一个指针:
One way to prevent this is defining it as an array instead of a pointer:
char p[] = "wikipedia";
p[0] = 'W'; // ok
为什么的char *
导致未定义的行为,而的char []
不?
Why does char*
cause undefined behaviour, while char[]
doesn't?
推荐答案
试图修改C字符串字面量的做的不的工作 - 阵列只能从一个括号初始化另外从字符串初始化,并且字符数组。
does not work -- arrays can only be initialized from a brace initializer, and char arrays additionally from a string literal.
这篇关于为什么字符*导致未定义的行为而的char []不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!