[英]In character Array Compiler giving extra space to store Null character but in string it's showing error
char ch[5] = {'a', 'b', 'c', 'd', 'e'}; 这没有显示任何错误但是 char ch[5] = "abcde" 显示错误。为什么?
#include <iostream>
using namespace std;
int main() {
char ch[5] = {'a', 'b', 'c', 'd', 'e'};
int i;
for( i = 0; ch[i] != '\0'; i++){
cout << ch[i] << ' ';
}
return 0;
}
Output:- ab c de In this case while loop is terminating implies null character is there but since I have given the size 5 so where it has stored this null character?
但是当我写这个程序时:-
#include <iostream>
using namespace std;
int main() {
char ch[5] = "abcde";
int i;
for( i = 0; ch[i] != '\0'; i++){
cout << ch[i] << endl;
}
return 0;
}
在这种情况下,它显示错误:- 字符数组的初始化字符串太长 [-fpermissive] 请解释为什么会发生这种情况。
循环终止意味着 null 字符存在,但由于我给出了大小 5,所以它在哪里存储了这个 null 字符?
这个数组中没有 null 字符,当你使用双引号时你只会得到一个(就像在你的第二个片段中一样)。
你越界访问了数组,很幸运(memory 中的下一个字节恰好是 null,这次没有召唤出鼻恶魔)。
但是 char ch[5] = "abcde" 显示错误。为什么?
因为 null 字符没有空间。
仅供参考,与 C++ 相比,C 在这方面没有那么严格,并且允许char ch[5] = "abcde";
. 在这种情况下没有添加 null 字符。
char ch[6] = "abcde";
尝试这个。 它需要一个额外的索引来存储'\0'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.