基本上我有这段代码:
#include <iostream>
using namespace std;
struct foo{
string *question;
//other elements
};
int main(){
foo *q;
foo *q2;
q->question = new string("This is a question");
//q2->question = new string("another question");
}
当我取消注释 q2->question = new string("another question");
时,它出错了,我不知道为什么。
更新:
该错误是一条 Windows 消息,指出程序已停止工作并打印 Process exited with return value 3221225477
最佳答案
您的 q
和 q2
指针未初始化。您正在尝试访问尚未分配的内存。作为短期修复:
int main(){
foo *q = new foo;
foo *q2 = new foo;
q->question = new string("This is a question");
q2->question = new string("another question");
// don't forget to release the memory you allocate!
delete q->question;
delete q2->question;
delete q;
delete q2;
}
在这种情况下更好的解决方案是不使用指针……完全没有必要。使用栈,不需要处理指针,也不需要释放内存。
int main(){
string q1 = "This is a question";
string q2 = "another question";
}
关于c++ - 奇怪的结构访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20807380/