why pointer to pointer is needed to allocate memory in function

前端 未结 9 1736
难免孤独
难免孤独 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:59

    In your first call to memory:

    void memory(int * p, int size)
    

    Realize that you are passing a VALUE to memory(), not an address. Hence, you are passing the value of '0' to memory(). The variable p is just a copy of whatever you pass in... in contains the same value but does NOT point to the same address...

    In your second function, you are passing the ADDRESS of your argument... so instead, p points to the address of your variable, instead of just being a copy of your variable.

    So, when you call malloc like so:

    *p = (int *)    malloc(size*sizeof(int));
    

    You are assigning malloc's return to the value of the variable that p points to.

    Thus, your pointer is then valid outside of memory().

    0 讨论(0)
  • 2020-12-28 20:00

    you dont need to use a pointer to pointer but a referenced pointer ie a * & not just *

    0 讨论(0)
  • 2020-12-28 20:06

    i corrected the code.. read the comment and all will be clear..

    #include<iostream>
    #include<conio.h>
    #include<exception>
    
    using namespace std;
    
    
    void memory(int* p, int size) {               //pointer to pointer` not needed
        try{
            p = new int[size] ;
        } catch(bad_alloc &e) {
           cout<<e.what()<<endl;   
        }
    }
    
    int main()
    {
        // int *p = 0;  wrong .. no memory assigned and then u are passing it to a function
        int *p;
        p = new int ;  // p = malloc( sizeof(int));
        /*before using a pointer always allocate it memory else
         you ll get frequent system crashes and BSODs*/
        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)<<"  ";
    
        getch();    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题