Init Array of vector.size() in c++ [duplicate] - c++

This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 6 years ago.
I try to compile some c++-Code from the internet
(http://arma.sourceforge.net/shadows/).
When compiling the code I get an error for initializing arrays.
Example (from the code-> GaussianMixtureModel.cpp Line:122):
void function()
{
int k = Vector.size();
uchar* Ptrs[k];
// Does somthing with the Ptrs
}
I also tried to edit it to the following:
const int k = Vector.size();
But it didn't work. I would appreciate any help!
I'm using Visual Studio 2012.
Thanks for your answers!

Arrays of variable length are not standard C++, they are a compiler extension in gcc and clang.
Looks like the code you are trying to compile needs to be compiled with one of the above.

What that piece of code is trying to use is called VLA - variable length array (yes, it's still variable in this context even if you make it const). You can read more about how it (doesn't) work in Visual Studio and why it doesn't here:
C++ Variable expressions for defining array size?
Enabling VLAs(variable length arrays) in MS Visual C++?

As Baum mit Augen pointed out, visual studio does not support a non-standard language extension for variable length arrays.
To make the program standard compliant, you can use a dynamically allocated array instead:
auto Ptrs = std::vector<uchar*>(k);
Some other changes may be necessary depending on how Ptrs is used.

In standard C++ you can only define arrays with a compile time constant length. That means, you can not use k, since it is determined at runtime. The code you got from the internet probably uses an extension called "variable length array" (VLA) which Visual Studio does not implement.
You could instead define a vector of uchar* if the semantics of the vector cleaning up its memory is the right thing in your case:
void function() {
auto vecSize = Vector.size();
auto Ptrs= vector<uchar*>(k, nullptr);
// Does somthing with the Ptrs
}

Related

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

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[]>.

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++

Declaring an array using const integer

I was trying to declare an int array in C++ and found this problem. The following code runs fine on g++ compiler but the compilation fails on Visual Studio. I was following Bruce Eckel and found this code.
#include<iostream>
int main()
{
const int j = std::cin.get();
char buf[j];
}
Keeping j just an int would be a problem, that I understand. Since the value of j would be const during the run-time, the program should get compiled. Please correct me if I am wrong anywhere.
Since the value of j would be const during the run-time, the program should get compiled.
No, the const-ness of j is irrelevant here. C++ currently only supports statically-sized C-arrays. Its size must be a compile-time constant.
If you want an array of dynamic size, use std::vector.
The fact that g++ by default compiles this is a bit unfortunate (for compatibility). You should use the -pedantic flag when using g++ to ensure that such compiler extensions aren’t enabled (using compiler extensions of course isn’t bad in itself, but in this case there’s not really any advantage).
You are trying to define buf as a variable-length array. This is a feature of C (not C++) that is supported by g++ as a non-standard extension. Evidently your other compiler does not support it.
I would suggest turning buf into std::vector<char> (or indeed std::string?)
Variable length arrays are C99 feature both gcc and clang supports them as an extension in C++ but Visual Studio never did and even though they recently added support for C99 is it not supported in C++
Since you are developing in C++ unless you have a good reason to not use it then std::vector or std::string should be sufficient.
I had the same problem. It seems very difficult to create an array of which its length is stored as a variable. What I did is create an additional function:
void Class:: initMyArray(const int size) {
myArray = new int[size]
}
Now, you just have to call that function and give it your variable. I'm not sure whether this is a proper solution though (I'm not a C++ expert).

Declaring local arrays using non-const variables to set the length, and it works? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
why a[n] is accepted in c during runtime?
Declaring the array size with a non-constant variable
I just wrote some code to test some other code and I needed an array as input data. As the size of the input data may differ, I declared the variable as follows:
float input[num_pixels_row][num_pixels_col][3];
where num_pixels_row and num_pixels_col are non-const variables which are set using input from the command line. I ran the code and it worked.
Then after a little while I noticed what I had just done and thought "Hey, wait a minute! This shouldn't work!!" But the strange thing is that it does. Since input is declared inside a function it should be allocated on the stack, but how can the compiler determine the stack frame if the size of the array isn't known?
I asked two colleagues and they were just as puzzled. By the way, I compiled the code using g++ 4.6.1
That's a gcc-specific compiler extension which makes your code sub-standard and nonportable. For example, this won't compile in Visual C++.
Variable length arrays are a part of the C99 specification, which gcc also allows in C++ programs.
I don't think this has been added to C++11 though, unfortunately. Though I'd suspect that since many C++ compilers also strive for C compliance that they'll end up supporting this as well.

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]