Declaring array of int

前端 未结 8 507
-上瘾入骨i
-上瘾入骨i 2020-12-07 13:11

Is there any difference between these two declarations?

int x[10];

vs.

int* x = new int[10];

I suppose th

8条回答
  •  再見小時候
    2020-12-07 14:04

    If you want to size an array dynamically, e.g.:

    void doSomething(int size)
    {
        int x[size];               // does not compile
        int *z  = new int[size];
        //Do something interesting ...
        doMore(z, size);
    }
    

    then x will not compile in C++, so you have to use z. The good news is that you can now use z, in most cases, as though it were statically allocated, e.g.:

    void doMore(int anArray[], int size)
    {
        // ...
    }
    

    takes z as an argument, treating the pointer as an array.

提交回复
热议问题