why pointer to pointer is needed to allocate memory in function

前端 未结 9 1766
难免孤独
难免孤独 2020-12-28 19:08

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 *          


        
9条回答
  •  执笔经年
    2020-12-28 19:42

    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<

提交回复
热议问题