why pointer to pointer is needed to allocate memory in function

前端 未结 9 1795
难免孤独
难免孤独 2020-12-28 19:08

I have a segmentation fault in the code below, but after I changed it to pointer to pointer, it is fine. Could anybody give me any reason?

void memory(int *          


        
9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 19:42

    You need a pointer to pointer because you need to return the value of the newly allocated pointer.

    There is three ways to return that value (2 if you use C):

    • use a pointer, here it is a pointer to pointer
    • use a reference, here it is a reference to pointer
    • use the return value of the function, so make memory return a int * instead of void

    The third way has definitely my preference.

    (and not, I won't admit you could also use a global, it's not a fourth way but an horror).

提交回复
热议问题