Array as array[n] and as pointer array*

后端 未结 2 1325
礼貌的吻别
礼貌的吻别 2021-01-14 07:22

What is the difference when array is declared as array[n] or as pointer array* according to example below? I guess that for example both \'a\' and \'c\' point at the first e

相关标签:
2条回答
  • 2021-01-14 07:50

    Long story short - they are essentially the same, but ever so slightly different.

    From what I've gathered from http://c-faq.com/aryptr/aryptr2.html , whilst they can both act as a pointer to the front of an array, when you declare an array as

    int a[3];
    

    you are essentially binding the size of '3' to your variable a, along with the fact it's an array. Hence, when you try to assign b, of size 5 to a, you get a compilation error.

    In contrast, when you write

    int * a;
    

    You are merely saying 'this is a pointer that may point to an array', with no promise on the size.

    Subtle, isn't it?

    0 讨论(0)
  • 2021-01-14 07:57

    The difference between the following two lines:

    int g[10];
    

    and

    int* h = new int[10];
    

    is that the second is dynamically-allocated, whereas the first is statically-allocated.

    For most purposes, they are identical, but where in memory they end up living is different.

    0 讨论(0)
提交回复
热议问题