首页 > 解决方案 > 为什么我的动态分配的数组不能在它的函数之外被访问?[C]

问题描述

我正在尝试访问array在函数fooA()中创建的main函数。我正在动态分配array使用malloc并指向它的传递指针,但主要指针不再指向相同的值。

int main() {
    int *test;
    fooA(test);
    printf("%d\n", test[0]);
    free(test);
}

void fooA(int *pass){
    int pass = malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        pass[i] = i;
    }
}

标签: cmalloc

解决方案


首先,代码中的问题......


void fooA(int *pass)  /*<<<<  pass is declared here */
{
    /* 
       however you have redefined pass as a different type here.
       This variable hides the previous definition of pass. 
       I'd suggest turning up the warning level on your compiler 
       to catch errors like this. (-Wall on gcc/clang, or warning 
       level 4 on Visual C)
     */
    int pass = malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        pass[i] = i;
    }
}

稍后当您调用该方法时,您会将 test 的副本传递给fooA,而不是对原始变量的引用。即您在 fooA 中对“传递”所做的任何更改都将作用于副本,而不是原始变量。

    int *test;
    fooA(test);

这里最简单的选择是简单地返回指针。

/* change the prototype to return the pointer instead of passing in as arg! */
int* fooA(void);

int main() {

    /* this should now be good */
    int *test = fooA();
    printf("%d\n", test[0]);
    free(test);
}

int* fooA(void){
    int* pass = malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        pass[i] = i;
    }
    return pass;
}

如果您想使用函数参数来执行此操作,则可以,但前提是您使用指向指针的指针,即

void fooA(int** pass);

int main() {
    int *test;
    fooA(&test); /*< passing address of test variable */
    printf("%d\n", test[0]);
    free(test);
}

void fooA(int** pass) {
    /* need to dereference pass here to modify the original pointer value */
    *pass = malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        (*pass)[i] = i;
    }
}

虽然这个问题被标记为 C,但为了完整起见,在 C++ 中,您可以通过引用传递变量(即在类型末尾添加 & 符号)

void fooA(int*& pass) {
    // working on the original variable, rather than a copy. 
    pass = (int*)malloc(5*sizeof(int));
    for(int i=0;i<5;i++){
        pass[i] = i;
    }
}

现在这段代码可以正常工作了:

    int *test;
    fooA(test);

推荐阅读