C ++中新内存的范围 [英] Scope of new memory in C++

查看:74
本文介绍了C ++中新内存的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试执行以下操作时,我收到一条错误消息,提示我正在尝试读取或写入受保护的内存.

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];
    ptr = ptr_b; 
}

void main() {
    int *ptr_a;
    func1(ptr_a);
    delete [] ptr_a;
}

这合法吗?

推荐答案

否.您正在犯一个常见的初学者错误.您不会记得指针只是按值传递的变量,除非您请求引用或指向它们的指针.将函数的签名更改为void func1(int *& ptr)

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)

这篇关于C ++中新内存的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆