退出函数时为什么动态分配函数参数的内存会丢失?

Pai*_*Han 0 c memory pass-by-value

我想在C中创建一个函数,它将为函数参数中的指针动态分配内存.

#include <stdio.h>
#include <stdlib.h>

int allocate(char * arr, int size){
    int code = -1;
    arr = malloc(size);
    if(arr != NULL) code = size;

    return code;    
}

void main(){
    char * array;

    if(allocate(array,4) != -1){
        printf("allocated!\n");

        if(array == NULL) printf("Oops it actually didn't allocate!\n");
    }
} 
Run Code Online (Sandbox Code Playgroud)

当我执行程序时; 它只会显示"已分配!" 和"哎呀它实际上没有分配!".这意味着内存分配确实发生了(因为函数的返回码不是-1.但是当我检查数组是否等于NULL时;它实际上是!

这是一个我已经遇到的编程问题,遗憾的是在某些情况下我无法使用像这样的char*allocate(char*arr,int size); 并将返回值赋给char*数组.

fre*_*ill 7

你缺乏间接水平,你需要char**.

原谅糟糕的格式,我用手机写的.

Char*数组,数组绑定到一个内存槽(它将包含一个指向另一个将被解释为char的内存槽的值).

因此,您将该值复制到函数并在allocate中本地修改该值,但修改永远不会到达外部范围.

#include <stdio.h>
#include <stdlib.h>

int allocate(char ** arr, int size){
    int code = -1;
    *arr = malloc(size);
    if(*arr != NULL) code = size;

    return code;    
}

void main(){
    char * array;

    if(allocate(&array,4) != -1){
        printf("allocated!\n");

        if(array == NULL) printf("Oops it actually didn't allocate!\n");
    }
} 
Run Code Online (Sandbox Code Playgroud)

在10年之内没做过C但是应该没问题.