快速的问题。C++ strlen()初始化字符数组
我找不到为什么一个初始化字符数组返回此值。据我所知,的strlen()函数将只返回字符的数量内的阵列,而不是规模,但为什么它会返回,如果有一个不包含字符?
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const int MAX = 50;
char test[MAX];
int length = strlen(test);
cout << "The current \'character\' length of the test array is: " << length << endl;
// returns "61"
// why?
cin >> test; //input == 'nice'
length = strlen(test);
cout << "The new \'character\' length of the test array is: " << length << endl;
// returns 4 when 'nice' is entered.
// this I understand.
return 0;
}
这是一个项目中我发疯了,因为我会试图用一个循环来将信息反馈到一个字符数组,但strlen的()总是会返回一个离谱的值,直到我初始化数组:
char testArray [50] ='';
代替
炭testArray [50];
我使用Visual Studio 2015年
多亏了这些成绩!
'char test [Max];'定义一个数组,但不是它的内容,在写入之前它仍然未初始化。读取未初始化的数据是未定义的行为。这意味着'strlen'今天可以返回61,明天5,崩溃或者做任何其他事情。要清楚的是,'strlen'返回找到字符''\ 0''前的字符数。 –
你期望发生什么,为什么? –
为什么你认为一个未初始化的数组不能包含离谱值? – Kevin