我是相当新的编程,仍然不知道为什么它发生或如何解决这个异常我正在运行这个程序我正在制作...如何异常发生?那么这里是代码:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
///////////////////////// SCREEN CLASS ////////////////////////////
class Screen
{
private:
/////////////////////////////////////////// Screen Variables //////////////
string _name;
string _contents[56];
public:
Screen(){};
~Screen(){};
//////////////////////////////////////////// Display ///////////////
void Display()
{
for (int I = 0; I <56; I++)
{
cout << _contents[I];
}
};
/////////////////////////////////////////// Insert ///////////////////////
bool Insert(vector <string> _string)
{
vector<string>::const_iterator I;
int y = 0;
for (I = _string.begin(); I != _string.end(); I++)
{
_contents[y] = _string[y];
y++;
}
return true;
};
};
///////////////////////////////////////////// Main ////////////////////////
int main()
{
vector <string> Map(56);
string _lines_[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};
int offset = 0;
for (vector <string>::const_iterator I = Map.begin(); I != Map.end(); I++)
{
Map[offset] = _lines_[offset];
offset++;
}
Screen theScreen;
theScreen.Insert(Map);
theScreen.Display();
char response;
cin >> response;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到了这个例外:
First-chance exception at 0x5acfc9c7 (msvcr100d.dll) in TestGame.exe: 0xC0000005: Access violation reading location 0xcccccccc.
Unhandled exception at 0x5acfc9c7 (msvcr100d.dll) in TestGame.exe: 0xC0000005: Access violation reading location 0xcccccccc.
Run Code Online (Sandbox Code Playgroud)
指向"memcpy.asm"中的这行代码:
185 rep movsd ;N - move all of our dwords
Run Code Online (Sandbox Code Playgroud)
谢谢!!
您创建了一个vector包含56个元素的元素:
vector <string> Map(56);
Run Code Online (Sandbox Code Playgroud)
然后定义一个包含五个string对象的数组:
string _lines_[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};
Run Code Online (Sandbox Code Playgroud)
然后你尝试string从该数组中读取56个对象:
v 56 elements between begin() and end()
for (vector <string>::const_iterator I = Map.begin(); I != Map.end(); I++)
{
Map[offset] = _lines_[offset];
^ reading from the I'th element of the array
Run Code Online (Sandbox Code Playgroud)
由于数组中只有五个元素,因此您正在读取未初始化的内存(或初始化但可能不包含string对象的内存)并将该内存视为包含string对象.
我不太确定你要做什么,但为什么不直接将字符串插入vector?
vector<string> Map;
Map.push_back("Hi");
Map.push_back("Holla");
// etc.
Run Code Online (Sandbox Code Playgroud)
或者使用std::copy算法:
int elements_in_lines = sizeof(_lines_) / sizeof(_lines_[0]);
std::copy(_lines_, _lines_ + elements_in_lines, std::back_inserter(Map));
Run Code Online (Sandbox Code Playgroud)