C Programming: malloc() inside another function

后端 未结 9 1207
暖寄归人
暖寄归人 2020-11-22 06:47

I need help with malloc() inside another function.

I\'m passing a pointer and size to the fu

9条回答
  •  滥情空心
    2020-11-22 07:07

    As mentioned in the other answers, we need a pointer to the pointer. But why?

    We need to pass the value by a pointer in order to be able to modify the value. If you want to modify an int, you need to pass it by the int*.

    In this question, the value we want to modify is a pointer int* (pointer changed from NULL to the address of the allocated memory), so we need to pass a pointer to the pointer int**.

    By doing followed, pInt inside foo(int*) is a copy of the argument. When we allocate memory to the local variable, the one in the main() is intact.

    void foo(int* pInt)
    {
       pInt = malloc(...);
    }
    int main()
    {
       int* pInt;
       foo(pInt);
       return 0;
    }
    

    So we need a pointer to pointer,

    void foo(int** pInt)
    {
       *pInt = malloc(...);
    }
    int main()
    {
       int* pInt;
       foo(&pInt);
       return 0;
    }
    

提交回复
热议问题