Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an int array with a non-const size

Tags:

c++

constants

I'm currently making a plugin for a game and I've got the following problem:

I want to let the user choose the radius, but since C++ doesn't let me create an array with a variable size I can't get a custom radius.

This works fine

        const int numElements = 25;
    const int arrSize = numElements * 2 + 2;
    int vehs[arrSize];
    //0 index is the size of the array
    vehs[0] = numElements;
    int count = GET_PED_NEARBY_VEHICLES(PLAYER_PED_ID(), vehs);

but this dosen't:

    int radius = someOtherVariableForRadius * 2;
    const int numElements = radius;
    const int arrSize = numElements * 2 + 2;
    int vehs[arrSize];
    //0 index is the size of the array
    vehs[0] = numElements;
    int count = GET_PED_NEARBY_VEHICLES(PLAYER_PED_ID(), vehs);

Is there any possible way of modifing that const int without creating errors in

int vehs[arrSize];

?

like image 306
Hx0 Avatar asked May 31 '26 00:05

Hx0


1 Answers

Array sizes must be compile-time constants in C++.

In your first version, arrSize is compile-time constant because its value can be calculated during compile-time.

In your second version, arrSize is not compile-time constant because its value can only be calculated at run-time (because it depends on user input).

The idiomatic way to solve this would be to use std::vector:

std::vector<int> vehs(arrSize);
//0 index is the size of the array
vehs[0] = numElements;

And to get the pointer to the underlying array, call data():

int count = GET_PED_NEARBY_VEHICLES(PLAYER_PED_ID(), vehs.data());
like image 143
emlai Avatar answered Jun 01 '26 15:06

emlai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!