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 *
memory(p, 10); //get the address of the pointer
this just send the p value not the adress of the p. it sends (*p). if addrees of p 123 and its value 50 it send 50 to the function.
and at the memory function it makes a new pointer with new adress like 124 and it contains 50; and it will allocate the memory and write the start of the allocated memory to 124 not 123 so p at the main still contains 50. So you did nothing!. You can control this with this code.
#include
#include
#include
using namespace std;
void memory(int* p, int size) { //*************pointer to pointer` is a must**********
try{
p = new int[size] ;
p[0]=100;
} catch(bad_alloc &e) {
cout<