一、三个区:全局区、栈区、堆区。
1、全局区:其的数据在程序结束后由系统释放
#include<iostream>
using namespace std;
//全局变量
int g_a = 10;
int g_b = 10;
//const修饰的全局变量
const int c_g_a = 10;
const int c_g_b = 10;
int main()
{
//全局区
//全局变量、静态变量、常量
//创建普通局部变量,即函数体里边的变量
int a = 10;
int b = 10;
cout << "局部变量中a的地址:" << (int)&a << endl;
cout << "局部变量中b的地址:" << (int)&b << endl;
cout << "全局变量中g_a的地址:" << (int)&g_a << endl;
cout << "全局变量中g_b的地址:" << (int)&g_b << endl;
//静态变量 在普通变量前面加static
static int s_a = 10;
static int s_b = 10;
cout << "静态变量中s_a的地址:" << (int)&s_a << endl;
cout << "静态变量中s_b的地址:" << (int)&s_b << endl;
//常量
//字符串常量
cout << "字符串常量的地址:" << (int)&"hello world" << endl;
//const修饰的变量
//const修饰的全局变量,const修饰的局部变量
cout << "全局常量c_g_a的地址:" << (int)&c_g_a << endl;
cout << "全局常量c_g_b的地址:" << (int)&c_g_b << endl;
const int c_l_a = 10;
const int c_l_b = 10;
cout << "局部常量c_l_a的地址:" << (int)&c_l_a << endl;
cout << "局部常量c_l_b的地址:" << (int)&c_l_b << endl;
system("pause");
return 0;
}
2、栈区:在函数执行完后自动释放
#include<iostream>
using namespace std;
//栈区的注意事项!!不要返回局部变量的地址
//栈区的数据由编译器管理开辟和释放
int* func(int b)//形参数据也会放在栈区
{
b = 100;
int a = 10;//局部变量 存放在栈区,栈区的数据在函数执行完后自动释放
return &a;//返回局部变量的地址
}
int main()
{
int* p = func(1);
cout << *p << endl;//第一次可以打印正确的数字,是因为编译器作了保留
cout << *p << endl;//第二次这个数据就不再保留
system("pause");
return 0;
}
3、堆区:由程序员释放
#include<iostream>
using namespace std;
int* func()
{
//利用new关键字 可以将数字开辟到堆区
//指针本质也是局部变量,放在栈区上,指针保存的数据是放在堆区
int* p = new int(100);
return p;
//return new int(100); //也可以简写为一句
}
int main()
{
int* p = func();
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
system("pause");
return 0;
}
二、new
1、new的基本语法
#include<iostream>
using namespace std;
//new的基本语法
int* func()
{
//在堆区创建数据类型
//new返回的是该数据类型的地址
int* p = new int(100);
return p;
}
void test01()
{
int* p = func();
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
//堆区的数据由程序员管理开辟、释放
//如果想释放堆区的数据,利用关键字delete
delete p;
//cout << *p << endl;//内存已经被释放,再次访问就是非法操作
}
int main()
{
test01();
system("pause");
return 0;
}
2、在堆区利用new开辟数组
#include<iostream>
using namespace std;
void test02()
{
//在堆区创建10整型数据的数组
int* arr = new int[10]; //10代表数组元素个数
for (int i = 0; i < 10; i++)
{
arr[i] = i + 100;//给10个元素赋值 100~109
}
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl;
}
//释放堆区数组
delete[] arr;
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}