C++ 0xC0000005:访问冲突读取位置0x00000000
我在一个字典项目上遇到了一个非常奇怪的问题。基本上,我得到了一个访问冲突错误: 0xC0000005:访问冲突读取位置0x00000000 当我尝试输入单词时失败-在这一行:C++ 0xC0000005:访问冲突读取位置0x00000000,c++,C++,我在一个字典项目上遇到了一个非常奇怪的问题。基本上,我得到了一个访问冲突错误: 0xC0000005:访问冲突读取位置0x00000000 当我尝试输入单词时失败-在这一行: cin >> wrd; 这是我的代码: void Menu::InsertWord(){ cout << "Please enter number of words: " << endl; int numberOFwords = InsertNum(); //Function th
cin >> wrd;
这是我的代码:
void Menu::InsertWord(){
cout << "Please enter number of words: " << endl;
int numberOFwords = InsertNum(); //Function that gets a number of words from the user.
Definition* word = new Definition[numberOFwords];
String wrd;
for (int i = 0; i < numberOFwords; i++){
cout << "Please enter a word: " << endl;
cin >> wrd;
void菜单::InsertWord(){
cout>(istream&is、String&other){
对于(int i=0;iother.string[i];
if(i==单词大小)
字符串[WORD_SIZE]='\0';
}
回报是;
}
ostream&operator您没有显示类字符串的默认构造函数,但我确信如果它存在,它会将数据成员字符串设置为NULL或nullptr
String wrd;
因此,当您使用运算符>>
cin >> wrd;
istream& operator >>(istream& is, String& other) {
for (int i = 0; i < other.size || i <= WORD_SIZE ; i++){
^^
您正在尝试访问未由类的对象分配的内存
我还认为这个条件在操作符的循环语句中>>
cin >> wrd;
istream& operator >>(istream& is, String& other) {
for (int i = 0; i < other.size || i <= WORD_SIZE ; i++){
^^
应该有
size = str.size;
而不是
size = Strlen(str.string);
因为str.string不是以零结尾的
而且完全不清楚函数Strcpy是如何工作的;它是否为字符串的副本动态分配内存
比较构造函数
String::String(const String& str){ //copy constractor.
size = Strlen(str.string);
string = Strcpy(str.string, size); //return a pointer to a string.
}
String::String(char* str) : string(str){
if (!string)
size = 0;
else{
size = Strlen(str);
string = Strcpy(str, size);
}
}
例如,这个赋值运算符(顺便说一下,在任何情况下都是错误的;例如,如果(!string&&str){,条件else的含义是什么?)
在Constructor中,您没有显式分配内存,而在assignment运算符中,您显式分配内存。因此,这看起来至少很奇怪。:0xC0000005:访问冲突读取位置0x00000000
您在某处取消引用空指针。在istream&operator>中设置断点(istream&is,String&other)
并查看other
参数状态。只要iDefinition*word=new Definition[numberOFwords];
不创建任何对象,只创建引用。
String& String::operator=(const char* str){
if (str){ //str ISN'T NULL
size = Strlen(str);
delete[] string;
string = new char[size + 1];
Strcpy(string, size);
}
else if (!string && str){
size = 0;
delete[] string;
string = NULL;
}
return *this;
}