为什么需要指针指针来在函数中分配内存

sky*_*oor 15 c++ malloc memory-management

我在下面的代码中有一个分段错误,但在我将其更改为指针指针后,它很好.有人能给我任何理由吗?

void memory(int * p, int size) {
    try {
        p = (int *) malloc(size*sizeof(int));
    } catch( exception& e) {
        cout<<e.what()<<endl;   
    }
}
Run Code Online (Sandbox Code Playgroud)

它在主要功能中不起作用

int *p = 0;
memory(p, 10);

for(int i = 0 ; i < 10; i++)
    p[i] = i;
Run Code Online (Sandbox Code Playgroud)

但是,它的工作方式是这样的.

void memory(int ** p, int size) {               `//pointer to pointer`
    try{
        *p = (int *)    malloc(size*sizeof(int));
    } catch( exception& e) {
        cout<<e.what()<<endl;   
    }
}

int main()
{
    int *p = 0;
    memory(&p, 10);       //get the address of the pointer

    for(int i = 0 ; i < 10; i++)
        p[i] = i;

    for(int i = 0 ; i < 10; i++)
        cout<<*(p+i)<<"  ";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Amb*_*ber 50

因为你想获得一个指针值从函数中完成的操作.malloc分配内存并为您提供该内存的地址.

在您的第一个示例中,您将该地址存储在本地参数变量中p,但由于它只是参数,因此它不会返回到主程序,因为C/C++ 默认是按值传递 - 即使对于指针也是如此.

Main      Function      malloc

  p         p            allocated
+---+     +---+         
| 0 |     | 0 |           A
+---+     +---+

becomes...

  p         p            allocated
+---+     +---+         
| 0 |     | ------------> A
+---+     +---+
Run Code Online (Sandbox Code Playgroud)

因此当主读取p时,它变为0,而不是A.

在您的工作代码中,您遵循传递给地址的指针,该地址为您提供主程序中指针变量的位置.您更新该地址处的指针值,然后主程序可以查找要用作其内存位置的值 - 从而将返回的地址传递malloc回主程序以供使用.

Main      Function      malloc

  p         p            allocated    
+---+     +---+         
| 0 |<------- |           A
|   |     |   |
+---+     +---+

becomes...

  p         p            allocated    
+---+     +---+         
|   |<------- |           
| ----------------------> A
+---+     +---+
Run Code Online (Sandbox Code Playgroud)

因此,当主要读取p时,它得到A.


Ark*_*kku 7

指针存储数据存储的地址.将指针传递给函数意味着为其提供数据的地址.但是,在调用之前,您没有数据地址malloc.所以你需要传递指针的地址(即指向指针的指针).这允许memory获取指针的地址p并设置p为指向它为数据分配的内存区域.