繁体   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