We can specify the size of the static array of the variable

Hi everyone, I want to ask that I read that we can only declare a dynamic array with a pointer and use malloc or newlike

int * array = new int[strlen(argv[2])]; 

but i wrote

 int array[strlen(argv[2])]; 

he did not give me an error

I read that a static array can only be declared by providing a constant size array, but here I gave a variable size to a static array

why so thanks


is it safe to use or is there a chance that in all the last stages this will create a problem, I use gcc linux

+5
source share
6 answers

What you have is called a variable length array (VLA), and it is not part of C ++, although it is part of C99. Many compilers offer this feature as an extension.

Even the newest C ++ 11 does not include VLA, since the whole concept doesn’t fit very well with the extended C ++ 11 type system (for example, what is decltype(array) ?), And C ++ offers -of library solutions for arrays run-time sizes that are much more powerful (e.g. std::vector ).

In GCC, compiling with -std=c++98/c++03/c++0x and -pedantic will give you a warning.

+12
source

Support for C99 variable length array , it defines c99 , section 6.7.5.2.

+5
source

What you wrote works on C99. This is a new addition called Variable Length Arrays. The use of these arrays is often discouraged because there is no interface through which distribution failure may occur ( malloc may return NULL , but if the VLA cannot be allocated, the program will be segfault or worse, behaves erratically).

+3
source
 int array[strlen(argv[2])]; 

This, of course, is invalid C ++ Standard code, because it defines a variable length array (VLA), which is not allowed in any version of the C ++ ISO standard. It is valid only in the C99. And in non-standard versions of the implementation of C or C ++. GCC provides VLA as an extension, also in C ++.

So, you have the first option. But don’t worry, you don’t even need it, as you have an even better option. Use std::vector<int> :

 std::vector<int> array(strlen(argv[2])); 

Use it.

+1
source

Some compilers are not fully compatible with C ++. What you specified is possible in MinGW (iirc), but this is not possible in most other compilers (e.g. Visual C ++).

What actually happens behind the scenes, the compiler modifies your code to use dynamically allocated arrays.

I would advise using such non-standard amenities.

+1
source

It's not safe. The stack is limited in size, and allocating from it based on user input like this has potential for.

For C ++ use std::vector<> .

Others answered why it "works."

+1
source

Source: https://habr.com/ru/post/916207/


All Articles