Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we give size of static array a variable

Tags:

c++

c

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

like image 981
mainajaved Avatar asked Oct 08 '11 11:10

mainajaved


People also ask

Can a static array have a variable size?

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).

Can the size of an array be a 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.

How do you change the size of an array that is static?

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.

How do you make an array variable size?

If you want to create an array whose size is a variable, use malloc or make the size a constant.


3 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 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.

like image 114
Kerrek SB Avatar answered Sep 19 '22 17:09

Kerrek SB


C99 support variable length array, it defines at c99, section 6.7.5.2.

like image 44
lostyzd Avatar answered Sep 18 '22 17:09

lostyzd


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).

like image 28
Pascal Cuoq Avatar answered Sep 21 '22 17:09

Pascal Cuoq