2017-02-26 187 views
-3

我昨天寫了這段代碼。它編譯/生成沒有錯誤的罰款,並打開Windows命令提示符,要求我輸入原始文本。我輸入我希望我的程序進行編碼的原始文本,然後按Enter鍵。這將導致以下錯誤:如何修復錯誤:EncodeTextApp.exe中0x00007FFC284DDDFF(ucrtbased.dll)引發的異常:0xC0000005

Exception thrown at 0x00007FFC284DDDFF (ucrtbased.dll) in EncodeTextApp.exe: 0xC0000005: Access violation writing location 0x00007FF7CAEC9C23.

If there is a handler for this exception, the program may be safely continued.

這上面的異常發生時,我輸入消息,我想在命令提示來編碼程序運行時。然後它只是崩潰。

下面的代碼是我的應用程序中的代碼。我不知道我在這裏做錯了什麼。

#include <stdlib.h> 
#include <conio.h> 
#include <iostream> 

#define MAX_LEN 80 
#define encodingshift 17 

char* encode(char* str) { 
    int i = 0; 
    while (str[i] != '\0') { 
     str[i] = str[i] - encodingshift; 
     /*str[i] = (char)((int)str[i] + encodingshift) % 26;*/ 
    } 
return (str); 
} 

void main() { 
    char *str = ""; 

    printf("Please enter the message to encode: "); 
    fgets(str, MAX_LEN, stdin); 
    char* original = str; 

    str = encode(str); 
    printf("\nOriginal Message: %s", original); 
    printf("\nEncoding Shift: %d", encodingshift); 
    printf("\nEncoded message: %s", str); 
    getchar(); 
} 

我所做的一切,從Visual Studio中卸載C++項目,並重新安裝它們,重新安裝整個的Visual Studio,但誤差不會消失。因此,我想知道我必須做什麼。這是阻止我執行程序的唯一因素。

+1

解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

+0

問題是我已經看過調試器。 – lobfil

+0

究竟是什麼時候*拋出異常? –

回答

3
​​

是錯誤的,str是一個字符串(tipically放在只讀段,因此,不能修改),你需要空間的字符串存儲與fgets,更改爲:

char str[MAX_LEN]; 

str = encode(str); /* str now is an array, you can not assign to */ 

encode(str); 

,請注意您沒有在while循環遞增i(無限循環)

而且,你混合C和C++,不這樣做,如果你想C,iostreamstdio.h和使用main的有效簽名:int main(void)而不是void main()

+0

您可能想要刪除最後一個段落,因爲OP現在已經將其作爲嚴格的C問題。 –

+0

@MartinBonner,這就是我說:'iostream'不是C頭:) –

+0

我,如果我要更換這一切 '''炭沒有得到*海峽=「」; printf(「請輸入要編碼的消息:」); 與fgets(STR,MAX_LEN,標準輸入);''' 具有以下: '炭STR [MAX_LEN];'或只是第一行。 – lobfil

相關問題