C++ dynamic arrays. Why does this one work? - c++

I was looking at this algorithm, the second one: Dynamic Programming Solution
http://www.geeksforgeeks.org/dynamic-programming-set-24-optimal-binary-search-tree/
It creates a dynamic array: int cost[n][n];
How does this work? I can run the code on GeeksForGeeks C++ emulator, but locally in Visual Studio I get the error "Expression must have a constant value".
What am I misunderstanding here? Doesn't C++ need to know the size of the array before compiling?

The code is not standard.
type name[runtime_size]
Is what is called a variable length array. This is not standard in C++ and will only compile in compilers that have an extension for this like g++ or clang. The reason this extension exists is it is valid in C99.
You are completely correct that the size of the array must be known at compile time. If you need an array and the size will not be know until run time I suggest you use a std::vector or a std::unique_ptr<type[]>.

Related

Why is it allowed to declare an automatic array with size depending on user input? [duplicate]

This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 4 years ago.
I'm using MinGW to compile for C++11 and I found out that this doesn't throw an error:
int S;
cin>>S;
char array[S];
While this does ("storage size of 'array' isn't known"):
char array[];
To me, the size is also unknown in the first case, as it depends on what the user input is.
As far as I knew, automatic arrays are allocated at compile time in stack memory. So why wouldn't the first example fail?
It's not. C++ doesn't have variable-length arrays, though some compilers allow it as an extension of the language.
You are apparently not aware of the GNU GCC extension Arrays of Variable Length. Therefore your first code compiles.
The error message is something different. You have to specify the array length.
gcc has the -pedantic switch - enabling this switch the compiler will report your first code as invalid:
warning: ISO C++ forbids variable length array ‘array’
Read also this thread What is the purpose of using -pedantic in GCC/G++ compiler?
Use very carefully compiler extensions because should you port your code to another compiler then you are in big trouble.
[This answers the original version of the question which asked about a static array; Deduplicator corrected this misconception, but now the question is missing a part.]
If your assumption that this piece of code defined a static array were correct, you'd be wondering for a good reason indeed: Something that is determined at compile time, like data with static storage duration, can obviously not depend on user input at run time. This truism is independent of any specific language.
The array defined in your code snippet has, by contrast, automatic storage duration, vulgo is created on the stack. A complete minimal working example would have made the case clearer: It would have shown that the code is in a function.
Objects with automatic storage duration can be created as needed at run time; there is no logical problem preventing that, which should fix your general headache ;-).
But note that, as some programmer dude correctly remarked, standard C++ nevertheless does not permit the definition of arrays whose size is not known at compile time; standard C does though, since C99. The rationale for C++ no following that amendment is that C++ provides better means for the use case, like the vector template. gcc, which is the compiler used in MinGW, permits this as an extension (and why not — it's available in the compiler anyway).

Visual Studio 2012 C++ arrays initialization using { }

i've just started programming in visual studio 2012 Express and from the beginning I'm having problems with arrays.
The environment says that this code is invalid:
int a[10] = {5,1,8,9,7, 2,3,11, 20,15};
First of all i had to declare that this array has fixed size using fixed keyword, but after that the program still has been wanting to put ; after a[10]. Filling up this array one number by one would be waste of time. Is it possible to work around it? I can't find any solution in google so I decided to post my problem here.
There's no fixed keyword in C++, perhaps in C#
The code you posted is perfectly valid in VS2012 Ultimate (and probably also Express)
From the above I might conclude you mismatched project and are trying to compile a C++ code in a C# environment.
Another reason that makes me think the above is the following error you get in a C# project if you try to compile the snippet above:
error CS0650: Bad array declarator: To declare a managed array the
rank specifier precedes the variable's identifier. To declare a fixed
size buffer field, use the fixed keyword before the field type.
which refers exactly to the fixed keyword you were trying to use.
Short story: you're trying to compile a C++ code in a C# project. Paste that code in a C++ project, not a C# one. Those are two different languages.
May be its too late to but you can use STL array for fix size arrays as
#include <array>
std::array<int, 5> ary { 1,2,3,4,5 }
This will be a fixed size array
As mentioned by Marco A. there is no "fixed" keyword in C++

error C2057: expected constant expression

Doing some AudioDSP in VC++ 2012 and am having problems with allocating memory for the buffer
int size = input.getSize();
float buf[size];
At compile I get the error "error C2057: expected constant expression" Looks like the code works in C99 just not C++. Any idea how to get around this?
That is because C99 supports variable length arrays, whilst C++ does not (at least, not C++98, nor C++11). Here are some workarounds:
Refactor your code to use a std::vector or any suitable container. If possible, this would be the preferred method.
Find a compiler that supports VLAs as an extension (for example, GCC with the option -std=c++gnu98 or -std=gnu++11).
Anyway, if you don't have that much code to refactor, please try to change your code to use a standard container instead of a VLA.

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

Creating array with constant

I was working on a program in Netbeans on Linux using a gcc compiler when, upon switching to Visual C++ on Windows 7, the code failed to compile as Visual C++ says it expected constant expression on several lines. On Netbeans, I simply did something similar to char name[fullName.size()];, while on Visual C++, I tried, among other things,
const int position = fullName.size();
char Name[position];
How can I create a constant to use for the array?
Note: I know about this question, but is there any way I can get this working without using vectors, since that would require a re-write of many parts of the program?
This is not possible in VC++. I know, pretty sad :(
The solutions include:
Create it on the heap
Make it constant
The new C++ standard (C++0x) proposes a 'constant expression' feature to deal with this. For more info, check this out.
In VC++ you can't do runtime declarations of stack array sizes, but you can do stack allocation via _alloca
so this:
const int position = fullName.size();
char Name[position];
becomes this:
const int position = fullName.size();
char * Name = (char*)_alloca(position * sizeof(char));
It's not quite the same thing, but it's as close as you are going to get in VC++.
C++ requires that the size of the array be known at compile time. If you don't mind using a non-standard extension, gcc does allow code like you're doing (note that while it's not standard C++, it is standard in C, as of C99).
I'd also guess that you could use a vector (in this particular place) with less trouble than you believe though -- quite a bit of code that's written for an array can work with a vector with only a re-compile, and little or no rewriting at all.
Your char name[fullName.size()]; is an example of a variable-length array which - as far as I know - are not standardized in C++ so you're at the mercy of the compiler.
[Slightly off-topic they're part of the C99 standard]