Question: I want to have an array in a function which retains its value when i exit the function i.e. for example-

```
 int func(int x)
 {
  static int arr[5];
 } 

```

But the problem is that i don't know the size of the array beforehand (i.e. it depends on x). So, i have to declare an array using 'new'. 

Can it be done like this?

```
 static int *arr=new int[x];

```

or will i have to do:

```
  static int *static arr = new int[x]

```

If not then
how to do that?

Answer: 
`static int *arr = new int[x];` is OK. However, you need to worry about memory leak since there is not a good point for `delete [] arr;`.

As described in comments, a local `static std::vector<int> arr;` is preferred since its destructor is called automatically at the end of the program.
I don't think thats legal.
The reason you can use variables to "dynamically" size an array inside function scope is AFAIK because the array gets put on the stack:

```
void foo(int x)
{
   int bar[x]; // this is legal
} // but goes out-of-scope here :-(

```

Declaring the array `static` destroys this. Think of it this way: The linker has no chance of knowing the size of the array, hence cannot locate anything "beyond" the array (clearly not desirable).

So basically you need to use the heap via `new` and `delete`. Or better yet use `std::vector<>` as already suggested (uses heap internally).