Creating a static array in C ++ at runtime

Is there a way to create a static array in C ++ at runtime. What I want is very simple, just want to get the input number from the user and create a static array of the size of the input number at runtime. No new operator is required, so that the pointer does not require only a static array?

+3
source share
6 answers

If you mean

unsigned size;
std::cin >> size;
int arr[size];

Then: No . C99 has a Variable-Length-Arrays function, but the C ++ 03 standard (and '0x) has no idea about this function.

+3
source

. static , (.. main). (aka created at run time). new, ( , ), , static. , (, std::vector, )

, , static. - , - , , main, .

+4

.

, . new .

+1

alloca , C99.

#include <iostream>
#include <alloca.h>
int main() {
        unsigned sz;
        std :: cin >> sz;
        int * p = static_cast<int*>(alloca(sz * sizeof(int)));
        // do stuff with p, do not attempt to free() it
}

C, . . , , .

+1

, static? , ?

, static ( ) , . , .

, , .

0

, , , static storage duration (.. ).

You cannot use the base array built into the language. The size of these objects is determined at compile time and cannot be changed at run time. But there are several alternatives.

The base std :: vector, probably you want:

std::vector<int>    data;

int main()
{
    int size;
    std::cout << "Input the size of the array\n";
    std::cin >> size;

    // This line sets the size of the container
    // vector is basically a C++ wrapper around a dynamically sized array
    data.resize(size);

    // Now we can safely read values into the array (like) container.
    for(int loop =0;loop < size;++loop)
    {
        std::cout << "Input Value " << loop << "\n";
        std::cin >> data[loop];
    }
}
0
source

All Articles