A quick c++ array initialization question using non const variable [duplicate] - c++

This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 9 days ago.
I am very new to C++ and I am wondering if I can do the following,
int a =5;
int b[a];
If so, what would happen if value of a changed? and any drawback using this.
If not,why it that?
thanks!
I tried the same code on an online c++ compiler and it does work. but i just dont know if this is a standard practice or not. if not, what would be the standard practices of refering a dynamic value to initialize an array?

No you cannot do that. Array bounds in C++ must be constants. This is legal
const int a = 5; // a is a constant
int b[a];
Some compilers do allow your code, but it is an extension to the C++ language called a variable length array or VLA.
But even on the compilers that do allow it, nothing happens to b if you change a, it will still have the same size as when it was created.
You can avoid all these issues by using a vector, like this std::vector<int> b(a); That is the correct way to do what you are asking for. You need to #include <vector> for the std::vector class.

Related

Why does C++ compiler allows to create an array of unknown size on stack at compile time? [duplicate]

This question already has answers here:
Disable variable-length automatic arrays in gcc
(2 answers)
In C++ books, array bound must be constant expression, but why the following code works?
(2 answers)
Closed 4 years ago.
I try to understand, what happens when creating an array of unknown size on stack at compile time. Let consider this code:
int main()
{
int x;
cin >> x;
int tab[x];
}
I found a lot of information about this saying that you can not create an array of unknown size on the stack, but I didn't find any information why does the C++ compiler allows it, or maybe some of them do? What happens when creating such array? Is it even created on stack or already on heap?
Does the GCC compiler have some option to turn on, thanks to which such a constructions would be considered as errors or at least warnings?
C++ does not permit Variable Length Arrays (VLAs).
However, the most recent C standard does, so it can sometimes be found as an extension, such as it is with the GCC.
When compiling, make sure so explicitly select a language (chose C++17 or later if you can) and ask for pedantic (strictly standards-conforming) behavior.

Has C++ Always Allowed Using A Variable for Array Size? [duplicate]

This question already has answers here:
In C++ books, array bound must be constant expression, but why the following code works?
(2 answers)
Closed 6 years ago.
For some reason, in the past, I recall not being able to do something like:
int arraySize;
cin >> arraySize;
int array[arraySize];
But recently, I tried this again and its not causing any issues. I could've sworn before this was something that threw an error in my compiler (macOS Sierra, Xcode 8.1). Was anything in the language updated to allow this? - I could be entirely remembering incorrectly and this wasn't an issue before, but I'm not sure. I thought array sizes had to be defined during compilation and the user couldn't pick that (which is where you would implement a dynamic array).
The C++ Standard does not support variable length arrays though some compilers can have their own language extensions that allow to use VLAs in a C++ program.
Thus this code snippet
int arraySize;
cin >> arraySize;
int array[arraySize];
is not C++ compliant.
Use instead the standard C++ class std::vector.
As for C then according to the C Standard implementations may conditionally support VLAs.
You can check whether an implementation supports VLAs.
From the C Standard (6.10.8.3 Conditional feature macros)
1 The following macro names are conditionally defined by the
implementation:
__STDC_NO_VLA__
The integer constant 1, intended to indicate that the implementation
does not support variable length arrays or variably modified types.
Was anything in the language updated to allow this
No. Variable length arrays (aka. VLAs) are a compiler specific extension.
The c++ standard never allowed this (unlike the c99 standard does so contrarily).

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

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
}

Differences with IDE/compilers array handling [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C/C++: Array size at run time w/o dynamic allocation is allowed?
I'm in a class where we have a simple assignment to write a function that returns a pointer to a dynamic array and provide a stub to test it. I have this done so I'm not asking for help with the assignment. On the class blog another student suggests that it is intuitive that one should be able to do int Array[size]; where size is apparently a user defined variable.
I know that in standard C++, at least according to my text, an array must have a "constant integer expression...greater than zero" as a size declarator. Which implies to me that their example can't work. In fact, with VS2010 you get three errors when you try.
However, they explain:
I know that, you know that, even the g++ compiler in my Ubuntu install
AND the Bloodshed compiler on my WinXP install know that. For certain
levels of "know that" one would expect "int Array[size];" to work
(like it has in both the prior classes).
But evidently it fails to run on some people's VS compilers. One can
only assume that, since the common denominator is VS (and yes, I
confirmed this by asking a friend to check it on HIS box), that VS is
the problem. One of several.
There's already confusion because the I know that... part is referring to me telling them that there shouldn't be any reason to #include <new> in order to use new, but it seems they think we agree that there shouldn't be any reason to use new to allocate a dynamic array.(?)
So the question is obvious. Are there any compilers which will accept int Array[size];, where size is not a const int without error?
int Array[size];
where size is not a constant expression is a variable length array. They're a standard feature of C as of the 1999 ISO standard. The C++ standard has not adopted them, but some compilers support them as a language extension.
(Any C++ compiler, when invoked in conforming mode, must at least issue a diagnostic for an array type with a non-constant size.)
Incidentally, this isn't directly related to the IDE you're using; it's controlled by the compiler that your IDE invokes.
As for #include <new> there is a standard header by that name, but it's not necessary for the new operator, which is built into the language. The <new> header provides several overloaded versions of operator new and a few other declarations.

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.