There is much documentation on the internet about always declaring arrays by constant values, eg. int array[10]; because
NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.
#include <iostream>
#include<cstdlib>
usingnamespace std;
int main(int argc, char** argv)
{
int n;
cout<<"\n Please enter array lenghth";
cin>>n;
int sir[n];
return 0;
}
This seems valid C/C++ code to me and it compiles on my machine. I am using GCC 4.3.2
Does declaring an array by a non-constant value seem correct to you?
Please try if this compiles on your compiler.
Thank you,
Andrei
It's not correct, the size must be a compile-time constant in C++.
However, GCC supports variable length arrays as an extension (note that C supports them since C99).
Yes, You can do that but before you as a number from a user, just define int n = 1 ( or anything)
Therefore, when user enter their value size will change.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include<cstdlib>
usingnamespace std;
int main(int argc, char** argv)
{
int n = 1;
cout<<"\n Please enter array lenghth";
cin>>n;
int sir[n];
return 0;
}
-pedantic
Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++.
[...]it finds some non-ISO practices, but not all---only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added.
A feature to report any failure to conform to ISO C might be useful in some instances, but would require considerable additional work and would be quite different from -pedantic. We don't have plans to support such a feature in the near future.
-pedantic-errors
Like -pedantic, except that errors are produced rather than warnings.
There is no guarantee that a vector is stored consecutively in memory. If you want dynamic memory allocation (for arrays) you should use new T[N], where T is the data type and N is the size. http://cplusplus.com/doc/tutorial/dynamic
If there is no guarantee that it is stored consecutively in memory, then why do vectors have a capacity and why must they reallocate when max capacity is reached? Wouldn't this suggest that they use consecutive memory locations to store information?