hello every one i want to ask that i have read that we can declare dynamic array only by using pointer and using malloc or newlike
int * array = new int[strlen(argv[2])];
but i have wrote
int array[strlen(argv[2])];
it gave me no error
i have read that static array can only be declared by giving constant array size but here i have given a variable size to static array
why is it so thanks
is it safe to use or is there chance that at any latter stages it will make problem i am using gcc linux
You cannot declare a static array of variable size because its space is allocated in the Data Segment (or bss segment in case of an uninitialized variable).
Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is defined at run-time. Variably modified types include variable length arrays and pointers to variable length arrays. Variably changed types must be declared at either block scope or function prototype scope.
An array that is declared with the static keyword is known as static array. It allocates memory at compile-time whose size is fixed. We cannot alter the static array. If we want an array to be sized based on input from the user, then we cannot use static arrays.
If you want to create an array whose size is a variable, use malloc or make the size a constant.
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 very new C++11 doesn't include VLAs, as the entire concept doesn't fit well into the advanced type system of C++11 (e.g. what is decltype(array)
?), and C++ offers out-of-the box library solutions for runtime-sized arrays that are much more powerful (like std::vector
).
In GCC, compiling with -std=c++98/c++03/c++0x
and -pedantic
will give you a warning.
C99 support variable length array
, it defines at c99, section 6.7.5.2.
What you have written works in C99. It is a new addition named "variable length arrays". The use of these arrays is often discouraged because there is no interface through which the allocation can fail (malloc
can return NULL
, but if a VLA cannot be allocated, the program will segfault or worse, behave erratically).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With