initialise variable sized array

Is there any way to initialize a variable sized array in a single line?

1
2
3
4
5
6
7
8
  int main()
{
    int n;
    cin>>n;
    int x[n]={};
    cout<<x[0];
}
As far as I know, the answer is no. Note that I'm not 100% sure about this...

But why do you want to do such a thing? Can't you use a simple for loop?
hmmm...
I wanted to know this just for the sake of knowledge.
First thing is that if you want to have variable sized array it has to be dynamic array, e.g. this:

int* x = new int[n];

than you can do something like this:

int* x = new int[y] {1, 2};

note that if the initialization is longer than array it will be resized. If you don't specife whole array some variables inside array will be unspecified(they won't have their own value; they will point to some junk from RAM). You can also use empty angle brackets to initialize whole array with 0.
rajroushan95 wrote:
Is there any way to initialize a variable sized array in a single line?

No, it's not possible. C standard 6.7.9p3 states
The type of the entity to be initialized shall be an array of unknown size or a complete
object type that is not a variable length array type


also, note that the following program is invalid:
1
2
    cin>>n;
    int x[n]={};

Either it's C++ and there are no VLAs or it's C and there is no cin >> n
Topic archived. No new replies allowed.