我定义了一个包含 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/