我寫了以下代碼:
#include <stdio.h>
int main() {
char s[10];
while (fscanf(stdin, "s", s) != 1) {
}
printf("%s", s);
}
但是代碼運行得很好。
這怎么樣?
緩沖區s大小為 10,但如果我輸入一個字串,例如helloworld10 個字符長,則printf陳述句將列印helloworld。這怎么可能?我認為它會列印出來helloworl,我認為它看起來像這樣:
index 0: h
index 1: e
index 2: l
index 3: l
index 4: o
index 5: w
index 6: o
index 7: r
index 8: l
index 9: \0
為什么這仍然對我有用?并列印helloworld?似乎空終止符甚至不存在。到底是怎么回事?
uj5u.com熱心網友回復:
在這一行:char s[10];
您要求并被分配了陣列中的 10 個位元組s。
所有其他資料都超出您的控制范圍,并且可能具有任何價值。
它可能被設備驅動程式或其他程式使用,甚至根本不是有效的記憶體。
然后使用你用值和終結符fscanf填充11個位元組。HelloWorld\0
這就是麻煩開始的地方。您的代碼填充了位元組#11,您沒有明確保留供您使用。
printf將列印一個字串,直到找到一個\0終止符。你沒有終結者的保證,所以任何事情都可能發生。
幸運的是,似乎有額外的位元組可用,并且沒有被任何其他任務/行程/執行緒/設備覆寫。\0文本的末尾恰好有一個,它的行為正常。但這是未定義的行為,任何事情都可能發生。
如果您的計算機列印了以下內容,那將是完全合法的:
HelloWorldPrepareForGozerTheGozerian
uj5u.com熱心網友回復:
只有你知道s緩沖區的大小。
s只是 fscanf 函式的指標。不管你的緩沖區有多大
index 0: h
index 1: e
index 2: l
index 3: l
index 4: o
index 5: w
index 6: o
index 7: r
index 8: l
index 9: d
index 10: \0
這是在執行緒堆疊中。它需要 11 個元素,但這對編譯器來說不是問題。只有你能在乎
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/516676.html
標籤:数组C指针扫描
下一篇:獲取此用戶輸入時我做錯了什么?
