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

标签 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

最佳答案

您的 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/

相关文章:

c++ - Xcode iPhone : Removing text from a . txt 文件

c++ - qt5从mysql数据库中选择数据

c++ - 创建自己的线程的 native 共享库可以(应该吗?)支持退出 'without warning' 的使用进程?

c++ - C++、Windows 中的简单 SSL 套接字

c - 使用指针访问嵌套结构中的成员。等效箭头运算符

c - 如何使用 posix_memalign 在 C 中正确对齐结构?

c++ - 使用指向数组的指针遍历对象数组

c++ - 如何在 Clojure 中创建 C 风格的结构体?

C结构体: typedef Doubt !

c# - 将预制类与原始类型 C# 配对的最佳方式