C Programming: malloc() inside another function

后端 未结 9 1276
暖寄归人
暖寄归人 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: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);
    }
    

提交回复
热议问题