开发者

can we give size of static array a variable

hello every one i want to ask that i have read that w开发者_运维技巧e 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


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


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜