gpt4 book ai didi

c++ - 奇怪的结构访问错误

转载 作者:太空宇宙 更新时间:2023-11-04 16:17:42 24 4
gpt4 key购买 nike

基本上我有这段代码:

#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

最佳答案

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

关于c++ - 奇怪的结构访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20807380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com