c++ - Creating an int array with a non-const size -


i'm making plugin game , i've got following problem:

i want let user choose radius, since c++ doesn't let me create array variable size can't custom radius.

this works fine

        const int numelements = 25;     const int arrsize = numelements * 2 + 2;     int vehs[arrsize];     //0 index size of array     vehs[0] = numelements;     int count = get_ped_nearby_vehicles(player_ped_id(), vehs); 

but dosen't:

    int radius = someothervariableforradius * 2;     const int numelements = radius;     const int arrsize = numelements * 2 + 2;     int vehs[arrsize];     //0 index size of array     vehs[0] = numelements;     int count = get_ped_nearby_vehicles(player_ped_id(), vehs); 

is there possible way of modifing const int without creating errors in

int vehs[arrsize]; 

?

array sizes must compile-time constants in c++.

in first version, arrsize compile-time constant because value can calculated during compile-time.

in second version, arrsize not compile-time constant because value can calculated @ run-time (because depends on user input).

the idiomatic way solve use std::vector:

std::vector<int> vehs(arrsize); //0 index size of array vehs[0] = numelements; 

and pointer underlying array, call data():

int count = get_ped_nearby_vehicles(player_ped_id(), vehs.data()); 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -