我有两种类型的数组初始化将用于字符串构造函数
int main() {
//char foo [] = { 'a', 'd' };
char foo[] = "ad";
std::string s = foo;
cout<<s;
int i;
cin >> i;
}
为什么在 char foo [] = { 'a', 'd' };
情况下我有输出:
ad╠╠╠╠╠╠R8$1↑■╬
当数组像 char foo [] = "ad";
这样初始化时,我有正常的输出 -ad
- 这在第一种情况下是预期的。
这两个数组初始化有什么区别,为什么第一个数组的输出中有垃圾?
最佳答案
你需要字符串以空结尾
char foo [] = { 'a', 'd', '\0' };
字符串文字已经以 null 结尾。
§ 2.14.5 String Literals
8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n
const char
”, where n is the size of the string as defined below, and has static storage duration14 After any necessary concatenation, in translation phase 7,
'\0'
is appended to every string literal so that programs that scan a string can find its end.
关于c++ - 数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32949403/