C++ 引发异常:访问冲突写入

  • 本文关键字:访问冲突 异常 C++ c++
  • 更新时间 :
  • 英文 :


在 LTestStr.exe: 0xC0000005:访问冲突写入位置0x00770000 0x008F1D0D引发异常。

在运行时尝试将一个数组中的一个字符放入另一个数组时会出现此错误。

输入字符串后立即发生错误,它不会关闭程序,只是"暂停"它。

#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] != ''); i++)
    {
        result[i] = test[i];    //Exception gets thrown here
    }
    if (strcmp(result, test) != 0)
    {
        cout << "Fail.";
    }
    else
    {
        cout << result << endl;
        cout << "Success.";
    }
    return 0;
}

我已经用评论标记了异常被抛出的位置。

该程序仅用于限制用户可以输入的内容,纯粹用于测试。但我不明白为什么这不起作用。

可能有一些功能可以为我做到这一点,但我仍在学习语言,我只是对尝试和测试我可以用循环等做什么感兴趣。

编辑

在提出建议后,我更改了 AND 运算符的 OR 运算符,并且不再收到错误。但是,我确实有一些非常奇怪的行为。

图片

test[i] != '?' || test[i] != ''总是true,所以你最终会超过数组的边界,因为i++增量太远。

您是否想要一个&&来代替||

最后,你需要插入一个显式的 NUL 终止符来result,否则输出将是未定义的。一种简单的方法是使用

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。

最新更新