3

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]
    
1
  • 2
    Some compilers will let you compile the second as an extension. Variable-length arrays are actually in C99. Commented Sep 9, 2012 at 5:13

2 Answers 2

2

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:

Sign up to request clarification or add additional context in comments.

5 Comments

Your link doesn't lead to anything except the home page.
@Rapptz what did you expect? A link to an illegal copy?
With all this link discussion, I find it worth pointing out that the site is now at stroustrup.com.
@Rapptz, no spoon fiddng please. Explore
@oldrinb No? He linked to a website that had a (presumably) previously working directory and now it doesn't.
1

To answer your questions:

1) Q: Why does the compiler have to know the size of arr in the above code?

A: If you generate assembly output, you'll notice a "subtract" of some fixed value to allocate your array on the stack

2) Q: Could I define int arr[m] i ... inside the function?

A: Sure you could. And it will become invalid the moment you exit the function ;)

Basically, you don't want an "array". A C++ "vector" would be a good alternative:

std::vector<A> v(5, A(2));

Here are a couple of links you might enjoy:

1 Comment

@paulsm4...In relation to your second answer...if it is a rule that the array bound must be a constant expression, how can the compiler allow 'm' as an array bound if its value is not known till runtime

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.