3

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];

?

3
  • 3
    Have you considered using std::vector? Commented Jul 18, 2015 at 4:38
  • I don't think it would work, definition of the GET_PED_NEARBY_VEHICLES function is: Image Commented Jul 18, 2015 at 4:40
  • 1
    @Hx0 std::vector has the data() member function just for that. Commented Jul 18, 2015 at 4:41

1 Answer 1

4

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());
Sign up to request clarification or add additional context in comments.

1 Comment

That worked out, thanks! I didn't know that vectors could solve this problem(Almost never used them before, pretty new to c++)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.