Scope of new memory in C++

前端 未结 3 1764
暗喜
暗喜 2021-01-14 11:08

When I try to do the following I get an error saying I\'m trying to read or write to protected memory.

void func1(int * ptr) {
    int *ptr_b = new int[5];
          


        
相关标签:
3条回答
  • 2021-01-14 11:33

    You passed the pointer by value. Which means that the pointer that the function works with is a local copy of the caller's pointer. And so the value you assign in the function cannot seen by the caller.

    Pass it by reference instead so that the function can assign to the caller's pointer rather than assigning to a local copy.

    void func1(int* &ptr)
    

    Or, perhaps consider returning the newly allocated pointer:

    int* func1()
    {
        return new int[5];
    }
    

    I'd prefer the latter approach.

    0 讨论(0)
  • 2021-01-14 11:40

    Change your signature to:

    void func1(int *& ptr)
    

    You're passing the pointer by value, so the outside ptr doesn't get changed. So it's like doing

    int main() {  // <--- main returns int
        int *ptr_a;
        delete [] ptr_a;
    }
    

    which is illegal, since ptr_a is not initialized.

    0 讨论(0)
  • 2021-01-14 11:52

    No. You're making a common beginner mistake. You're not remembering that pointers are just variables that are passed by value unless you ask for a reference or pointer to them. Change the signature of your function to void func1(int *& ptr)

    0 讨论(0)
提交回复
热议问题