为什么在C中的函数调用之后变量的值会丢失?

Cof*_*Pro 1 c pointers memory-leaks

为什么在执行函数"test"之后传递的变量"list"为空,即访问列表元素或释放指针列表会导致内存泄漏?

我错过了什么?

int test(int** container)
{
    int numOfItems = 2;
    int* p1;
    int* p2;
    int j=0;

    container = (int**) malloc (sizeof(int*) * numOfItems);
    for(j=0;j<numOfItems;j++)
         container[j] = (int*) malloc (sizeof(int));

    *(container[0]) = 12;
    *(container[1]) = 13;
}

int main( int argc, const char* argv[] )
{ 
    int* list;
    test(&list);
}
Run Code Online (Sandbox Code Playgroud)

Cho*_*tch 7

container = (int**) malloc (sizeof(int*) * numOfItems);
Run Code Online (Sandbox Code Playgroud)

应该

*container = malloc (sizeof(int*) * numOfItems);
Run Code Online (Sandbox Code Playgroud)

container只是一个局部变量,一个副本int* list.

另外,你一般不应该投回报malloc.