Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring an dynamic size array

Tags:

c++

arrays

If I want to declare a dynamic size array in the main function, I can do:-

 int m;
 cin>>m;
 int *arr= new int[m];

The following cannot be done as while compiling the compiler has to know the size of the every symbol except if it is an external symbol:-

 int m;
 cin>>m;
 int arr[m];

My questions are:

  1. Why does the compiler have to know the size of arr in the above code? It is a local symbol which is not defined in the symbol table. At runtime, the stack takes care of it(same way as m). Is it because the compiler has to ascertain the size of main() (a global symbol) which is equal to the size of all objects defined in it?

  2. If I have a function:

    int func(int m)
    

    Could I define int arr[m] inside the function or still I would have to do

    int *a= new int[m]
    
like image 372
AvinashK Avatar asked Dec 21 '25 00:12

AvinashK


1 Answers

For instance :

int MyArray[5]; // correct

or

const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct

but

int ArraySize = 5;
int MyArray[ArraySize]; // incorrect

Here is also what is explained in The C++ Programming Language, by Bjarne Stroustrup :

The number of elements of the array, the array bound, must be a constant expression (§C.5). If you need variable bounds, use a vector (§3.7.1, §16.3). For example:

like image 126
shail Avatar answered Dec 23 '25 13:12

shail