Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a vector to a struct's vector field

I'm not sure why this works:

main.cpp:

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

Gen.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;
}

Previously, I removed the pointers to TF_info and double list, and just had the line:

  TF_info.pwm = double_list;

... which resulted in a SegFault. What is the point of creating and assigning the pointers (pointer and pointer2) to each other?

like image 516
J.W. Avatar asked Mar 03 '14 01:03

J.W.


People also ask

Can I make a vector of structs?

You can actually create a vector of structs!

How do you convert a struct to an array in Matlab?

C = struct2cell( S ) converts a structure into a cell array. The cell array C contains values copied from the fields of S . The struct2cell function does not return field names. To return the field names in a cell array, use the fieldnames function.

What is vector in C programming?

Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.


1 Answers

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

and

TF_info.pwm = double_list;

are totally equivalent!


The only line which could possibily cause a segfault is:

std::cout << TF_info.pwm[1] << std::endl;
like image 54
Sebastian Hoffmann Avatar answered Oct 05 '22 05:10

Sebastian Hoffmann