为什么需要指向指针的指针才能在函数中分配内存 [英] why pointer to pointer is needed to allocate memory in function

查看:116
本文介绍了为什么需要指向指针的指针才能在函数中分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码中存在分段错误,但是在将其更改为指针指针之后,这很好.有人可以给我任何理由吗?

I have a segmentation fault in the code below, but after I changed it to pointer to pointer, it is fine. Could anybody give me any reason?

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

它在主要功能中不起作用

it does not work in the main function as blow

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

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

但是,它的工作原理是这样的.

however, it works like this .

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;
}

推荐答案

因为您希望从函数中完成的操作中获取指针值 back . malloc分配内存并为您提供该内存的地址.

Because you're wanting to get a pointer value back from the operations done in the function. malloc allocates memory and gives you an address for that memory.

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

In your first example, you store that address in the local argument variable p, but since it's just the argument, that doesn't make it back to the main program, because C/C++ are pass-by-value by default - even for pointers.

Main      Function      malloc

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

becomes...

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

因此,当main读取p时,它的值为0,而不是A.

and thus when main reads p, it gets 0, not A.

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

In your working code, you follow the pointer passed to an address, and that address gives you the location of the pointer variable in the main program. You update the pointer value at that address, which the main program can then look up the value of to use as its memory location - thus passing the address returned by malloc back to the main program for use.

Main      Function      malloc

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

becomes...

  p         p            allocated    
+---+     +---+         
|   |<------- |           
| ----------------------> A
+---+     +---+

因此,当main读取p时,它将获得A.

and thus when main reads p, it gets A.

这篇关于为什么需要指向指针的指针才能在函数中分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆