Scope of new memory in C++

前端 未结 3 1788
暗喜
暗喜 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.

提交回复
热议问题