Hey guys. I've been doing some assignment in Visual Studio 2012 Ultimate that I have recently installed, and I'm having problems with understanding a few things. One of those things is this:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace std;
int main()
{
int n;
cin >> n;
string output[n];
}
While I remebember that a code like this worked perfectly in CodeBlocks, Visual Studio gives me an error in the line 10:
The compiler creates your array at compile time which means that the value of n must be known at compile time. Because n is a non const variable the value of n can change, so its value is not known at compile time. using a non const variable to crate an array is illegal in c++.
@Yanson - How so? Even in c++ shell which you can open from this very window you can declare array with a non-const variable. Why is it possible here and in code-blocks, but not possible in Visual Studio?
@pogrady Explained it in a good way about 2 years ago.
When you declare array like this:
int myArray[10];
the compiler needs to know at compile time what the size of the array is, because it is going to set a block of memory in the local store aside for you to use.
To create arrays dynamically, you need to create memory on the free store, and you do this using the "new" keyword in c++
Basically. Something like this -
1 2 3 4 5 6
int n;
cin >> n;
string* output = new string[n];
output[0] = "hello";
cout << endl << output[0] << endl;
Also, like @Yanson said. You have to include #include <string>
How so? Even in c++ shell which you can open from this very window you can declare array with a non-const variable. Why is it possible here and in code-blocks, but not possible in Visual Studio?
just because your compiler allows you to do something does not mean it is legal c++ code. In codeblocks set the compiler flag [-pedantic - errors] and codeblocks will give you an error for this as well as visual studio.
in your project select
settings
compiler
then check the box that says
treat as errors the warnings demanded by strict ISO c++ [-pedantic -errors]