[英]I can't understand char[] behavior in C++
向堆棧溢出社區致意。 我試圖從最基礎的方面學習C ++,並且遇到了一些奇怪的(至少對我來說)行為。 這是我的“你好世界”
#include <iostream>
int main()
{
std::cout << "Enter Thing! " << std::endl;
char Thing[]="";
std::cin >> Thing;
std::cout << "Thing is " << Thing << "!" << std::endl;
int i=0;
while (i <= 10)
{
++i;
std::cout << "Thing is " << Thing << " in " << i << " while!" << std::endl;
std::cout << "i is " << i << "!" << std::endl;
}
std::cout << "Thing is " << Thing << " after while!" << std::endl;
std::cout << "i is " << i << ".5!" << std::endl;
}
真正困擾我的是它提供的輸出。
Enter Thing!
thing
Thing is thing!
Thing is t☺ in 1 while!
i is 1!
Thing is t☻ in 2 while!
i is 2!
Thing is t♥ in 3 while!
i is 3!
Thing is t♦ in 4 while!
i is 4!
Thing is t♣ in 5 while!
i is 5!
Thing is t♠ in 6 while!
i is 6!
Thing is t in 7 while!
i is 7!
Thing is in 8 while!
i is 8!
Thing is t in 9 while!
i is 9!
Thing is t
in 10 while!
i is 10!
Thing is t♂ in 11 while!
i is 11!
Thing is t♂ after while!
i is 11.5!
我真的不明白那里發生了什么。 甚至更多,例如,如果我添加“用於”構造
for (int i=4; i <=7; ++i)
{
std::cout << "i is " << i << "!" << std::endl;
std::cout << "Thing is " << Thing << " for!" << std::endl;
}
std::cout << "i is " << i+3 << ".5!" << std::endl;
std::cout << "Thing is " << Thing << " after for!" << std::endl;
輸出更改為更奇怪的事情
Enter Thing!
thing
Thing is thing!
Thing is thing☺ in 1 while!
i is 1!
Thing is thing☻ in 2 while!
i is 2!
Thing is thing♥ in 3 while!
i is 3!
Thing is thing♦ in 4 while!
i is 4!
Thing is thing♣ in 5 while!
i is 5!
Thing is thing♠ in 6 while!
i is 6!
Thing is thing in 7 while!
i is 7!
Thing is thin in 8 while!
i is 8!
Thing is thing in 9 while!
i is 9!
Thing is thing
in 10 while!
i is 10!
Thing is thing♂ in 11 while!
i is 11!
Thing is thing♂ after while!
i is 11.5!
i is 4!
Thing is t♦ for!
i is 5!
Thing is t♣ for!
i is 6!
Thing is t♠ for!
i is 7!
Thing is t for!
i is 14.5!
Thing is after for!
可能是我愚蠢或某事,但是如果我什至不能使最基本的事情都起作用,我就無法繼續學習。 抱歉,如果某個問題已經解決,請盡我最大的努力尋找答案,但沒有成功。 所以,你會高興地指出我在哪里嗎? 謝謝。
PS我在Win7x64m下使用NetBeans 8和Cygwin。
Thing
變量是僅包含一個字符的數組。 向其寫入多個字符將超出范圍並導致不確定的行為 。
空字符串文字""
是一個包含單個字符的數組,即字符串終止符,編譯器將使用該數組將Thing
數組初始化為精確的副本。
基本上,您有兩種解決方案,要么聲明數組的大小較大:
char Thing[128] = "";
或者您使用標准的C ++字符串類 :
std::string Thing;
我絕對推薦后一種解決方案。
這是有問題的:
char Thing[]="";
您正在創建一個包含單個字符的空數組,並將用戶輸入寫入其中。
第一次您偶然有正確的輸出,但是隨后數據被覆蓋,您得到了這個奇怪的輸出。
創建具有足夠緩沖區長度的字符串
char thing[256];
或使用字符串對象。
正如其他答案所建議的那樣,您無需真正初始化就可以使用char
數組(提供固定大小)。 此外,這是C風格的編程。 我強烈建議使用C ++的std::string
而不是char
-Array,因為這不會那么容易出錯。
由於代碼已編譯,因此在本地聲明的此類數組的大小應固定。
char Thing[] = "";
這給您一種幻想,“事物”的大小是可變的。 遺憾的是,“物”的大小將根據右邊給出的初始值自動推導出,這使您輸入的字符串寫在內存中的意外位置,從而導致不確定的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.