Scope of new memory in C++

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

提交回复
热议问题