c++ - std::list.begin() 给出空指针

标签 c++

我定义了一个包含 std::list 的结构。在我的代码中,我尝试遍历此列表,但得到了一些奇怪的结果。

struct my_struct_t {
    std::list<int> my_list;
    //More fields
};

这是我的头文件中定义的结构。

包含此 header 的文件中的一些示例代码为:

    std::list<int>::iterator my_iterator;

    struct my_struct_t* test_struct = (struct my_struct_t*) malloc(sizeof(struct my_struct_t));
    my_iterator = test_struct->my_list.begin();
    printf("Beginning of list address: %p\n", my_iterator);

    my_iterator = test_struct->my_list.end();
    printf("End of the list address: %p\n", my_iterator);
    printf("Address of the list: %p\n", &(test_struct->my_list));

此代码编译并运行良好,但输出将类似于:

Beginning of list address: (nil)
End of the list address: 0x86f010
Address of the list: 0x86f010

最后两行对我来说很有意义,因为列表应该是空的。但是我如何/为什么一开始就得到一个空指针?我该如何解决这个问题?

最佳答案

您不能malloc 一个列表,然后在没有初始化的情况下使用它。这是一个无效的操作。

尚未使用正确的 new 调用对其进行初始化。这在不引发段错误的情况下完全有效,真是太神奇了。

您将需要使用 C++ 样式初始化创建您的 my_struct_t 对象,否则它将无法工作。

您是否尝试过更多 C++,例如:

struct my_struct_t* test_struct = new my_struct_t;

当然,稍后您将删除而不是免费调用。

关于c++ - std::list.begin() 给出空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14974308/

相关文章:

c++ - [C++] 导入文本文件 - getline() 的问题

c++ - 浮点运算的精度

c++ - 如何从线程函数返回值?

c++ - 如何在两个 float 之间找到最短的十进制数

c++ - 如何为 Linux 部署 Qt 应用程序

c++ - 对短字符串编码的有理数执行算术运算时 float 的简单替代方法

c++ - c++构造函数中的段错误

c++ - 为什么/什么时候应该使用 C++ 中的作用域运算符在我的类之外声明方法?

c++ - 合并多个 csv 文件

C++ 继承 : child class instance uses both child and parent constructors