Declaring array of int

前端 未结 8 491
-上瘾入骨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:01

    The only thing similar between

    int x[10];
    

    and

    int* x = new int[10];
    

    is that either can be used in some contexts where a int* is expected:

    int* b = x;   // Either form of x will work
    
    void foo(int* p) {}
    
    foo(x);      // Either form will work
    

    However, they cannot be used in all contexts where a int* is expected. Specifically,

    delete [] x;  // UB for the first case, necessary for the second case.
    

    Some of the core differences have been explained in the other answers. The other core differences are:

    Difference 1

    sizeof(x) == sizeof(int)*10   // First case
    
    sizeof(x) == sizeof(int*)     // Second case.
    

    Difference 2

    Type of &x is int (*)[10] in the first case

    Type of &x is int** in the second case

    Difference 3

    Given function

    void foo(int (&arr)[10]) { }
    

    you can call it using the first x not the second x.

    foo(x);     // OK for first case, not OK for second case.
    

提交回复
热议问题