2016-04-30 119 views
1

我試圖讀取使用與fgets如下char值:「周圍的變量堆棧被損壞」錯誤

int main() { 
    char m_cityCharCount; 

    // Input the number of cities 
    fgets(&m_cityCharCount, 4, stdin); 
    return 0; 
} 

Visual Studio中返回該錯誤代碼被執行後 - Stack around the variable m_cityCharCount was corrupted

是有什麼我可以做的呢?

+0

大小char'的'是在C 1,不4.修改的示例:'炭m_cityCharCount [16];與fgets(m_cityCharCount,的sizeof m_cityCharCount,標準輸入);'' – BLUEPIXY

+1

fgets'旨在讀零結尾*字符串*。您正在使用一個「char」作爲接收緩衝區,它只對一個空的以零結尾的字符串足夠。在做這件事的時候,你用'4'來騙'fgets'。您的接收緩衝區只包含'1'' char',而不是'4'。 – AnT

回答

1

第一個參數是緩衝區指針(它的尺寸要大或等於比第二個參數的sizeof,但(焦)== 1)。

int main() { 
    char m_cityCharCount[4]; 

    // Input the number of cities 
    fgets(m_cityCharCount, 4, stdin); 
    return 0; 
} 
2

m_cityCharCount是一個字符,它最多可以容納一個字符,但你告訴fgets它是4字節緩衝區。即使您只輸入了回車鍵,fgets也會將新行和空終止符存儲到緩衝區,這是造成嚴重問題的原因。你需要一個更大的緩衝做fgets:與fgets()的

char str[4096]; 
fgets(str, sizeof str, stdin);