why pointer to pointer is needed to allocate memory in function

前端 未结 9 1796
难免孤独
难免孤独 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:59

    In C, you have only pass-by-value. So your function memory() gets it own local-only copy of p. malloc inside memory() assigns only to the copy of p that is local to the function. When memory() returns to main(), the copy of p from main is unchanged. In C++, you solve this by using pass-by-reference, like this:

    void memory(int*& p, int size)

    In C, you use double pointers to achieve similar results.

提交回复
热议问题