[英]C program produces weird output
在我學習 CI 的過程中,我決定創建一個結構體,該結構體給出了我在其中提供的魚的大小,我的問題是為什么當我編寫這段代碼時:
#include <stdio.h>
#include <string.h>
struct fish
{
char catfish[9]; //reserve memory for 9 chars
char goldfish[10]; //reserve memory for 10 chars
char mackrel;
char oldfish;
};
int main()
{
struct fish typeof_fish;
strcpy(typeof_fish.catfish, "Big Fish\n");
strcpy(typeof_fish.goldfish, "Small Fish\n");
printf("%s\n", typeof_fish.catfish);
return 0;
}
輸出產生“大魚小魚”輸出在這里
然而,當我重寫最上面的一段代碼並更改 char catfish[9] 時; 燒焦鯰魚[10] :
#include <stdio.h>
#include <string.h>
struct fish
{
char catfish[10]; //reserve memory for 10 chars
char goldfish[10]; //reserve memory for 10 chars
char mackrel;
char oldfish;
};
int main()
{
struct fish typeof_fish;
strcpy(typeof_fish.catfish, "Big Fish\n");
strcpy(typeof_fish.goldfish, "Small Fish\n");
printf("%s\n", typeof_fish.catfish);
return 0;
}
提前感謝您對這個令人費解的錯誤的回答
當您 strcpy "Big Fish\\n"
時,您沒有為catfish[9]
的空終止符留出足夠的空間。 該字符串有 9 個字符長,這意味着您需要一個大小為 10 的緩沖區來存儲空終止符。
如果字符串錯過了空終止符,則輸出具有未定義的行為,因為程序無法知道字符串在哪里結束。
當您執行第一次復制時, strcpy()
總共復制 10 個字節(來自字符串本身的 9 個字節加上終止符)。 由於您在catfish
只分配了 9 個字節,因此終止符進入goldfish
的第一個字節,然后在您復制第二個字符串時被覆蓋。 因此,當您執行catfish
的printf()
時,它不會在catfish
的末尾停止,而是繼續打印,直到在goldfish
的末尾找到終止符。
在第二種情況下,您為終止符添加了足夠的空間,以免被覆蓋,因此當您打印時,它只會按預期打印catfish
的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.