簡體   English   中英

引發C ++異常:編寫訪問沖突

[英]C++ Exception thrown: Access violation writing

在whileLTestStr.exe中的0x008F1D0D處引發的異常:0xC0000005:訪問沖突寫入位置0x00770000。

嘗試將一個數組中的一個字符放入另一個數組時,在運行時會出現此錯誤。

輸入字符串后立即發生錯誤,它不會關閉程序,只是“暫停”它。

#include "stdafx.h"
#include <iostream>
#include <cstring>

int main()
{
    using namespace std;

    char test[20];
    char result[20];
    int i = 0;

    cout << "Enter a string without symbolic characters: ";
    cin.get(test, 20);

    for (i; (test[i] != '?' || test[i] != '\0'); i++)
    {
        result[i] = test[i];    //Exception gets thrown here
    }

    if (strcmp(result, test) != 0)
    {
        cout << "Fail.";
    }
    else
    {
        cout << result << endl;
        cout << "Success.";
    }

    return 0;
}

我已經在注釋中標記了拋出異常的位置。

該程序僅用於限制用戶輸入內容,僅用於測試。 但是我不明白為什么這行不通。

可能有一些功能可以為我完成此操作,但是我仍在學習該語言,我只是想嘗試並測試我對循環等所做的事情。

編輯

提出建議后,我將OR運算符更改為AND運算符,但不再收到錯誤。 但是,我確實得到了一些奇怪的行為。

圖片

test[i] != '?' || test[i] != '\\0' test[i] != '?' || test[i] != '\\0'始終為true ,因此隨着i++增量過大,您最終會越過數組的邊界。

您是否要用&&代替||

最后,您需要為result插入一個顯式的NUL終止符,否則輸出將是不確定的。 一種簡單的方法是使用以下命令將數組初始化為\\0的數組

char result[20] = {};
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    using namespace std;

    string test;

    cout << "Enter a string without symbolic characters: ";
    getline(cin, test);

    if (test.find("?") != string::npos )
    {
        cout << "Fail.";
    }
    else
    {
        cout << test << endl;
        cout << "Success.";
    }
}

這就是使用std :: string的方式。 學習C ++,而不是C。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM