c++基础入门笔记12内存四区

113 阅读1分钟

1.内存分区模型

不同区域的数据有不同的生命周期,给予我们更大的灵活编程。

2.栈区

int * student() {
	int age=10;
	return &age;//指针也是局部变量
};

int main() {
	int * p = student();
	cout << *p << endl;//第一次输出正确了,是因为编译器做了保留
	cout << *p << endl;//指针里的值不见了,输出乱码
	cout << student() << endl;
	cout << student() << endl;//多次调用,多次编译
	system("pause");
	return 0;
}

3.堆区

使用new关键字在堆区开辟内存

new 数据类型

注意new出来的数据它返回来的是对应的类型指针

int * student() {
	int * age=new int(10);
	/*把10这个数据放在了堆区,并把地址给age指针,因为指针指向的值是由程序员释放,
	所以,指针指向的值不变。*/
	return age;
};

int main() {
	int * p = student();
	cout << *p << endl;
	cout << *p << endl;//结果没有改变
	system("pause");
	return 0;
}

4.new关键字的使用方法

void student() {
	int * age=new int[10];//小括号和中括号的区别
	age[0]=10;
	cout<<age[0]<<endl;
};

int main() {
	student();
    system("pause");
	return 0;
}

因为指针本就是一个数据类型,所以必须有返回值,不能用void *

除了自己来释放堆区的内存,还可以用delete 来释放

void student() {
	int * age=new int[10];//小括号和中括号的区别
	age[0]=10;
	cout<<age[0]<<endl;
	delete[] age;//数组在堆区的释放
};

int * stu() {
	int * age=new int(10);
	return age;
};
void st(){
    int *p=stu();
    cout<<*p<<endl;
    delete p;
    //无法再用cout<<*p<<endl;,会报错
}