c++ - 将 vector 分配给结构的 vector 字段

标签 c++ pointers vector struct segmentation-fault

我不确定为什么会这样:

主要.cpp:

int main(int argc, char * argv[]) {
    Pwm_Info tf_info;
    tf_info = get_pwm_info(library_data, motif_name);
}

生成.cpp

        struct Pwm_Info {
    std::string motif_name;
    int width;
    std::vector < double > pwm;
    Pwm_Info(): motif_name(0),
    width(0),
    pwm(0) {}
}
TF_info;

Pwm_Info get_pwm_info(std::string library_data, std::string motif_name) {
    std::vector < double > double_list;
    strtk::parse(pwm_block, " \n\r", double_list);
    std::cout << double_list.size() << std::endl;

    Pwm_Info TF_info;

    TF_info.motif_name = motif_name;
    TF_info.width = n_width;

    std::vector < double > * pointer;
    std::vector < double > * pointer2;

    pointer = & TF_info.pwm;
    pointer2 = & double_list; * pointer = * pointer2;
    std::cout << TF_info.pwm[1] << std::endl;
    TF_info.pwm = double_list;
    return TF_info;
}

之前,我删除了指向 TF_info 和双列表的指针,只有一行:

  TF_info.pwm = double_list;

... 这导致了段错误。 创建指针(pointer 和 pointer2)并将其分配给彼此有什么意义?

最佳答案

pointer = &TF_info.pwm;
pointer2 = &double_list;
*pointer = *pointer2;

TF_info.pwm = double_list;

完全等价!


唯一可能导致段错误的行是:

std::cout << TF_info.pwm[1] << std::endl;

关于c++ - 将 vector 分配给结构的 vector 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22136082/

相关文章:

c++ - 将 Lua 函数传递给 C++

c++ - 开源可执行编辑器

c++ - 将 itkImage 保存为 DICOM 时未写入图像位置/方向

c++ - 在另一个结构中声明一个结构

c++ - 引用、 vector 、std::vector::at 和易于使用的接口(interface)

c - 如果使用用户定义函数和 main() 函数访问全局声明的数组元素,为什么会得到不同的值?

c++ - 使用函数声明初始化函数指针 - 可能吗?

C 帮助 : Compiler gives me a "makes pointer from integer without cast" when using strlen()

c++ - 结构初始化数组

c++ - 访问 vector 时出现运行时错误