Declaring array of int

前端 未结 8 523
-上瘾入骨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 13:49

    First one is an array of int of size 10. Saying that its created on stack is wrong. Because the Standard doesn't guarantee that. Its implementation-defined. Its storage duration could be static or automatic depending on whether x is global variable or local variable.

    In the second one, you create a pointer of type int*. Not necessarily created on heap, the Standard doesn't say that. The allocated memory spans over 10 * sizeof(int) bytes. For this you've to deallocate the memory yourself, by writing:

    delete [] x; 
    

    In this case, the memory of the pointer x is dynamically allocated, and dynamically deallocated, so such objects is said to have dynamic storage duration.

提交回复
热议问题