gpt4 book ai didi

C++ 异常抛出 : Access violation writing

转载 作者:行者123 更新时间:2023-11-27 23:50:06 25 4
gpt4 key购买 nike

Exception thrown at 0x008F1D0D in whileLTestStr.exe: 0xC0000005: Access violation writing location 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 运算符,并且不再出现错误。但是,我确实遇到了一些非常奇怪的行为。

PICTURE

最佳答案

测试[i] != '?' || test[i] != '\0' 始终为 true,因此您最终会越过数组的边界,因为 i++ 递增太多。

您是否需要 && 代替 ||

最后,您需要在 result 中插入一个明确的 NUL 终止符,否则输出将是未定义的。一种简单的方法是使用

将数组初始化为 \0 的数组
char result[20] = {};

关于C++ 异常抛出 : Access violation writing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47177406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com