c++ - 尝试创建结构对象,在位置 0x3FE00000 中创建访问冲突写入错误
问题描述
我正在学习使用结构并制作基于文本的 RPG,并且我知道项目应该是我的代码中的一个类,但是,因为我使用的是结构,而且我是 C++ 新手,而且我不懂编程我的代码到底出了什么问题以及如何修复它,错误发生在我尝试创建一个名为 player 的结构对象的地方。(我也想为我乱七八糟的代码道歉,我在乱搞,一旦我得到了我的工作,我就会清理它。)
这是我的第一次尝试,我没有尝试太多,因为我不确定到底要尝试什么。
#include "pch.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct item {
double resistance, attack;
string name;
};
item none, WoodenBoots, LeatherChestplate, WoodenShield, WoodenClub, WoodenSword;
struct mobs {
int health, attack;
double droprate, resistance;
item drops[3];
};
item GetData(string object);
int main()
{
none.attack = 0;
none.resistance = 0;
none.name = "none";
WoodenBoots.resistance = .05;
WoodenBoots.attack = 0;
WoodenBoots.name = "Wooden Boots";
LeatherChestplate.resistance = .2;
LeatherChestplate.attack = 0;
LeatherChestplate.name = "Leather Chestplate";
WoodenShield.resistance = .1;
WoodenShield.attack = 0;
WoodenShield.name = "Wooden shield";
WoodenClub.resistance = 0;
WoodenClub.attack = 1.2;
WoodenClub.name = "Wooden Club";
WoodenSword.resistance = .05;
WoodenSword.attack = 1.5;
WoodenSword.name = "Wooden Sword";
mobs goblin;
goblin.attack = 1;
goblin.health = 10;
goblin.droprate = .5;
goblin.resistance = .1;
goblin.drops[1] = WoodenClub;
goblin.drops[2] = WoodenShield;
goblin.drops[3] = WoodenBoots;
mobs Alpha_Goblin;
Alpha_Goblin.attack = 2;
Alpha_Goblin.health = 15;
Alpha_Goblin.droprate = .5;
Alpha_Goblin.resistance = .1;
Alpha_Goblin.drops[1] = WoodenSword;
Alpha_Goblin.drops[2] = WoodenShield;
Alpha_Goblin.drops[3] = LeatherChestplate;
struct pdata {
item Playeritem[6];
item PlayerWeapon;
}player;
player.PlayerWeapon = WoodenSword;
cout << player.PlayerWeapon.name << endl;
player.PlayerWeapon = GetData("weapon");
player.Playeritem[0] = GetData("sheild");
player.Playeritem[1] = GetData("head");
player.Playeritem[2] = GetData("torso");
player.Playeritem[3] = GetData("legs");
player.Playeritem[4] = GetData("feet");
player.Playeritem[5] = GetData("hands");
string weapon = player.PlayerWeapon.name;
cout << weapon << endl;
system("pause");
}
我希望它能够创建结构并继续定义结构内的项目值。我在 struct pdata 的最后一行收到以下错误:在 Structure.exe 中的 0x57115139 (vcruntime140d.dll) 处引发异常:0xC0000005:访问冲突写入位置 0x3FE00000。
解决方案
在 C++ 中,数组的索引从零到 num_elements - 1
所以如果你声明
int myArray[3];
然后尝试访问:
myArray[3] = 5;
根据您的编译器和调试设置,您将获得可能表现为访问冲突的未定义行为。
在 Visual Studio 中,您可以在调试运行时使用异常设置并检查访问冲突异常,并在抛出异常之前暂停执行。
推荐阅读
- c# - 在 SpecFlow 测试中使用 ChromeDriver
- java - ExoPlayer 直播在 Askey Android 电视盒上冻结,音频继续
- javascript - 如何在滚动时隐藏标题导航,并在滚动停止时显示
- selenium - 如何在 reportng(html 文件)中添加堆栈跟踪以通过测试?
- google-compute-engine - 谷歌计算引擎没有响应
- java - 如何使用 JavaFX 导出应用程序,以便没有它的用户可以运行该应用程序
- ios - Сocoapods 中继 URL 无法下载
- php - 获取基于 get_the_ID() 的自定义分类标签(外部 for 循环)
- angular8 - 如何将非数组的非数组元素绑定到数组?
- makefile - gnu makefile:配方中的shell函数执行顺序