Does declaration of array require a fixed size?

Dear all,

As I know in C++, when we declare an array, we need a constant size as:
int arr[4];
or
#define SIZE 4;
int arr[SIZE].

This is likely due to the fact that the size of arrays must be known in compilation time.

However, I've realized that it is executable if get the size of an array from the keyboard (it means arrays size can be input in the run-time).

Here is an example code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  // Example program
#include <iostream>

int main()
{
  unsigned n;
  int arr[n];
  std::cout<<"Specify the value of n:";std::cin>>n;
  for(unsigned ii=0;ii<n;++ii){
    arr[ii]=ii*10;   
  }
  for(unsigned ii=0;ii<n;++ii){
    std::cout<<arr[ii]<<"\t";   
  }
  std::cout<<std::endl;
}

Is it a new update of C++ (even with compile C++98 it works) or I misunderstand somewhere?

Thanks.
No, it is not.
What you do is a fatal mistake if you input a number that is greater than the array size. I'm surprised it compiles for you though.

Also :
unsigned n;
The variable is undefined.
Last edited on
Firstly, my question is if the declaration of arrays with changeable sizes is possible ? As I know (you can follow this tutorial http://www.cplusplus.com/doc/tutorial/arrays/) it says:

NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.


Secondly, the variable is undefined because it takes value from keyboard input.

Thanks.
Use a dynamic allocated array bro. You are playing with fire and death here.
http://www.learncpp.com/cpp-tutorial/6-9a-dynamically-allocating-arrays/
Is it a new update of C++ (even with compile C++98 it works) or I misunderstand somewhere?

No. what is happening (most likely) is you are making use of a non-standard compiler extension.
https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

If you use the g++ compiler,
use the -pedantic or -pedantic-errors flags when compiling.
http://stackoverflow.com/a/17899408

In C++, use a std::vector instead.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>

int main()
{
    unsigned n;
    std::cout<<"Specify the value of n:";std::cin>>n;
    
    std::vector<int>  arr(n);
    
    for (unsigned ii=0;ii<n;++ii) {
        arr[ii] = ii*10;
    }
    
    for (unsigned ii=0;ii<n;++ii) {
        std::cout<<arr[ii]<<"\t";   
    }
    std::cout<<std::endl;
}
Last edited on
Topic archived. No new replies allowed.