C Programming: malloc() inside another function

后端 未结 9 1086
暖寄归人
暖寄归人 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:02

    How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?

    Ask yourself this: if you had to write a function that had to return an int, how would you do it?

    You'd either return it directly:

    int foo(void)
    {
        return 42;
    }
    

    or return it through an output parameter by adding a level of indirection (i.e., using an int* instead of int):

    void foo(int* out)
    {
        assert(out != NULL);
        *out = 42;
    }
    

    So when you're returning a pointer type (T*), it's the same thing: you either return the pointer type directly:

    T* foo(void)
    {
        T* p = malloc(...);
        return p;
    }
    

    or you add one level of indirection:

    void foo(T** out)
    {
        assert(out != NULL);
        *out = malloc(...);
    }
    

提交回复
热议问题