mainajaved
mainajaved

Reputation: 8163

can we give size of static array a variable

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

Upvotes: 11

Views: 6788

Answers (6)

tenfour
tenfour

Reputation: 36896

It is not safe. The stack is limited in size, and allocating from it based on user-input like this has the potential to overflow the stack.

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

Others have answered why it "works".

Upvotes: 1

Pascal Cuoq
Pascal Cuoq

Reputation: 80266

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

Upvotes: 3

Paul Manta
Paul Manta

Reputation: 31567

Some compilers aren't fully C++ standard compliant. What you pointed out is possible in MinGW (iirc), but it's not possible in most other compilers (like Visual C++).

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

I would advice against using this kind of non-standard conveniences.

Upvotes: 1

lostyzd
lostyzd

Reputation: 4523

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

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 476950

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.

Upvotes: 18

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361302

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

It is certainly not valid C++ Standard code, as it is defining a variable length array (VLA) which is not allowed in any version of C++ ISO Standard. It is valid only in C99. And in a non-standard versions of C or C++ implementation. GCC provides VLA as an extension, in C++ as well.

So you're left with first option. But don't worry, you don't even need that, as you have even better option. Use std::vector<int>:

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

Use it.

Upvotes: 1

Related Questions