why pointer to pointer is needed to allocate memory in function

Posted by skydoor on Stack Overflow See other posts from Stack Overflow or by skydoor
Published on 2010-04-12T22:21:55Z Indexed on 2010/04/12 22:22 UTC
Read the original article Hit count: 366

Filed under:
|
|

Hi

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

© Stack Overflow or respective owner

Related posts about c

    Related posts about malloc