奇怪的struct访问错误

时间:2013-12-27 20:28:23

标签: c++ struct

基本上我有这段代码:

#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

3 个答案:

答案 0 :(得分:3)

您的qq2指针未初始化。您正在尝试访问尚未分配的内存。作为短期解决方案:

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";
}

答案 1 :(得分:1)

foo *q;
foo *q2;

在这些指针上使用间接时,您将获得未定义的行为,因为这些指针尚未初始化(即它们未指向有效的地址)。

你需要让它们指向一个对象:

foo* q  = new foo();
foo* q2 = new foo();

// don't forget to delete

或者只使用堆栈分配:

foo q;
foo q2;

q.question = "This is a question";

答案 2 :(得分:1)

您没有为qq2分配内存。

替换

foo *q;
foo *q2;

foo *q = new foo();
foo *q2 = new foo();

最后,删除所有创建的对象:

delete q->question;
delete q;
delete q2->question;
delete q2;