Dynamically allocating array explain

前端 未结 7 1896
忘了有多久
忘了有多久 2020-12-13 11:53

This is sample code my teacher showed us about \"How to dynamically allocate an array in C?\". But I don\'t fully understand this. Here is the code:

int k;
i         


        
7条回答
  •  盖世英雄少女心
    2020-12-13 12:06

    Remember that arrays decays to pointers, and can be used as pointers. And that pointers can be used as arrays. In fact, indexing an array can be seen as a form or pointer arithmetics. For example

    int a[3] = { 1, 2, 3 };  /* Define and initialize an array */
    printf("a[1] = %d\n", a[1]);  /* Use array indexing */
    printf("*(a + 1) = %d\n", *(a + 1));  /* Use pointer arithmetic */
    

    Both outputs above will print the second (index 1) item in the array.

    The same way is true about pointers, they can be used with pointer arithmetic, or used with array indexing.

    From the above, you can think of a pointer-to-pointer-to.type as an array-of-arrays-of-type. But that's not the whole truth, as they are stored differently in memory. So you can not pass an array-of-arrays as argument to a function which expects a pointer-to-pointer. You can however, after you initialized it, use a pointer-to-pointer with array indexing like normal pointers.

提交回复
热议问题