How can I use arrays of map which nested in arrays of structure?

I have the below code for creating arrays of structure which contains arrays of map.My question is how to add new value to the map?And how to update value to exiting key?

struct Line {
        map<int, vector<float>> *con_inf;
        float *points_x; // Array
        float *points_y; // Array
        int points_num;
    };
void update_map(int points_length) {
    struct Line *line_struct = NULL;
    line_struct = (struct Line *)malloc(sizeof(int) *points_length);
    for (int line_struct_idx = 0; line_struct_idx < points_length; line_struct_idx++) {
        line_struct[line_struct_idx].con_inf = (map<int, vector<float>> *) malloc(sizeof(int) *points_num);
        line_struct[line_struct_idx].points_x = (float *) malloc(sizeof(int) *points_num);
        line_struct[line_struct_idx].points_y = (float *) malloc(sizeof(int) *points_num);
        line_struct[line_struct_idx].points_num = points_num;
    }
}

I use code below to confirm that the key exits.True for non-existent

if (line_struct[cur_line_idx].con_inf[cur_point_idx].count(con_line_idx) == 0) {
    // add value
} else {
    // update value
}

But sometimes it does not work.Something that obviously doesn't exist will get the False result( mean existint).When the code going to update value,I will get the Segmentation fault (core dumped).


line_struct = (struct Line *)malloc(sizeof(int) *points_length);

This is clearly wrong. You are allocating an array of the Line structs but use sizeof(int) instead of sizeof(Line) for some reason. Usage of such array is a clear undefined behavior, so no wonder that you are get segfaulted.

First of all, better avoid using direct memory allocation for arrays at all by using std::vector instead.

Secondary malloc is just a memory allocation. Using it to create dynamic objects (like std::map) is a really bad idea (and UB as well) - no constructors will be run, so result object will be in the indeterminate state. If you really must manage memory manually, use new/delete operators, or even better - smart pointers std::unique_ptr/std::shared_ptr