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