快速的問題。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