why pointer to pointer is needed to allocate memory in function

前端 未结 9 1767
难免孤独
难免孤独 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 your first call to memory:

    void memory(int * p, int size)
    

    Realize that you are passing a VALUE to memory(), not an address. Hence, you are passing the value of '0' to memory(). The variable p is just a copy of whatever you pass in... in contains the same value but does NOT point to the same address...

    In your second function, you are passing the ADDRESS of your argument... so instead, p points to the address of your variable, instead of just being a copy of your variable.

    So, when you call malloc like so:

    *p = (int *)    malloc(size*sizeof(int));
    

    You are assigning malloc's return to the value of the variable that p points to.

    Thus, your pointer is then valid outside of memory().

提交回复
热议问题