C Programming: malloc() inside another function

后端 未结 9 1094
暖寄归人
暖寄归人 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;
    }
    
    0 讨论(0)
  • 2020-11-22 07:15

    If you want your function to modify the pointer itself, you'll need to pass it as a pointer to a pointer. Here's a simplified example:

    void allocate_memory(char **ptr, size_t size) {
        void *memory = malloc(size);
        if (memory == NULL) {
            // ...error handling (btw, there's no need to call free() on a null pointer. It doesn't do anything.)
        }
    
        *ptr = (char *)memory;
    }
    
    int main() {
       char *data;
       allocate_memory(&data, 16);
    }
    
    0 讨论(0)
  • 2020-11-22 07:22

    The only way I could get pointer to a pointer solution to work for a similar problem I was having for this function

        BOOL OpenBitmap2 ( LPCTSTR pszFileName, char** pszBMPFile)  
    

    Was by assigning a temporary pointer to store the address

        char* BMPFile;
        { BMPFile = (char*)GlobalAlloc(GPTR, dwFileSize + 1);   // allocate storage using GlobalAlloc + 1 for null term string
    

    then reassigning it

        {* pszBMPFile = BMPFile; return (0);} // Error = False
    

    Any comment on why using "* pszBMPFile" directly with GlobalAlloc didn't work would be appreciated. I answered my own question. I forgot to carry the "*" through with pszBMPFile in the other lines of code. Good lessons from all the contributors. Many thanks.

    0 讨论(0)
提交回复
热议问题