To set the size of an array to a variable

Asked 2 years ago, Updated 2 years ago, 26 views

int cnt;
const int * cntptr = &cnt;

cin >> cnt;

int arr[*cntptr];

I can't...

Is there any way to receive the size of a variable as a variable> ㅠ<

c++

2022-09-21 18:55

2 Answers

The C++ standard determines the size of the array at compile time. Therefore, the size of the array cannot be determined by general variables, but must be determined by compilation time constants.

Instead, you have vector, a container with variable sizes similar in characteristics to the array.

You can think of vector as a variable size arrangement, and the method of use is almost similar. We provide resize() for resizing.

int cnt;
cin >> cnt;
std::vector<int> arr(cnt);

The C++ standard does not allow you to size an array through variables, but some compilers do support it through options. In the C99 standard, it is possible to size the array through variables, but C++ does not allow this because it does not completely contain the contents of C language.


2022-09-21 18:55

If the goal is to create any sequence, Since it is C++, if you assign it dynamically with the new keyword, it will be possible to create an array that is sized as a variable at runtime.

#include <iostream>

int main()
{
    int size;
    std::cin >> size;

    int *arr = new int[size];
    delete[] arr;

    return 0;
}


2022-09-21 18:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.