gpt4 book ai didi

c++ - gdb: with c++ vector

转载 作者:行者123 更新时间:2023-11-30 00:53:07 29 4
gpt4 key购买 nike

我在访问 std vector 的内存时遇到问题。

我先定义一个结构体(在头文件中):

typedef struct Systems {
// other variables...
vector <double> sum;
} System;

我需要一个系统集合,每个 vector 和必须包含 num doubles 所以,在主要部分,我写:

System * system;
system = (System*)malloc(DIM_ENSEMBLE*sizeof(System));
for (i =0; i< DIM_ENSEMBLE; i++) {
//...
system[i].part_sum.resize(num);
//...
}

从这一点开始,我一使用

System[0].part_sum[0]

为了初始化 vector ,我收到了一个段错误程序。

如果在 gdb 中,我会尝试

(gdb) print system[0].part_sum[0]

我得到:

$2 = (double &) @0x200000003: <error reading variable>

我使用 reserve 或 allocator 而不是 resize 得到了同样的错误。我还检查了 vector 的容量

cout << system[0].part_sum.capacity();

我播种有很多空间......

发生了什么事?这是内存管理的问题吗?

A.

最佳答案

用 vector 替换你的指针:

std::vector<System> system(DIM_ENSEMBLE);

for (i =0; i< system.size(); ++i) {
//...
system[i].part_sum.resize(num);
//...
}

您不能使用malloc 初始化System 数组,因为System 不是POD。它的 vector 数据成员需要通过构造函数调用来构造。上面的例子解决了这个问题。

请注意,如果你想传递一个指向 vector 底层数据的指针以使用一些遗留 API,你可以通过

const System* cp = system.data(); // or &system[0] if no C++11 
System* p = system.data(); // or &system[0] if no C++11

例如:

void doStuff(System*, unsigned count);

std::vector<System> test(42);
doStuff(test.data(), test.size()); // C++11
doStuff(&test[0], test.size()); // C++03

关于c++ - gdb: <error reading variable> with c++ vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17346621/

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