1.1 程序运行前
/*
* @Author: Heweifu
* @Date: 2021-09-26 23:06:01
* @LastEditTime: 2021-09-26 23:09:31
* @LastEditors: Heweifu
* @Description: 内存分区测试
* @FilePath: \C++核心编程\1内存分区模型\1_1程序运行前.cpp
*/
#include <iostream>
using namespace std;
//全局变量
int g_a = 10;
int g_b = 10;
//全局常量
const int c_g_a = 10;
const int c_g_b = 10;
int main()
{
//局部变量
int a = 10;
int b = 10;
//打印地址
cout << "局部变量a地址为: "<< (long long)&a <<endl;
cout << "局部变量a地址为: "<< (long long)&b <<endl;
cout << "全局变量g_a地址为: "<< (long long)&g_a <<endl;
cout << "全局变量g_b地址为: "<< (long long)&g_b <<endl;
//静态变量
static int s_a = 10;
static int s_b = 10;
cout << "静态变量s_a地址为: "<< (long long)&s_a <<endl;
cout << "静态变量s_b地址为: "<< (long long)&s_b <<endl;
cout << "字符串常量1地址为: "<< (long long)&"hello world" <<endl;
cout << "字符串常量2地址为: "<< (long long)&"hello world1" <<endl;
cout << "全局常量c_g_a地址为: "<< (long long)&c_g_a <<endl;
cout << "全局常量c_g_b地址为: "<< (long long)&c_g_b <<endl;
//局部常量
const int c_l_a = 10;
const int c_l_b = 10;
cout << "局部常量c_l_a地址为: "<< (long long)&c_l_a <<endl;
cout << "局部常量c_l_b地址为: "<< (long long)&c_l_b <<endl;
system("pause");
return 0;
}
结果:
1.2程序运行后
/*
* @Author: Heweifu
* @Date: 2021-09-26 23:25:49
* @LastEditTime: 2021-09-26 23:33:10
* @LastEditors: Heweifu
* @Description: 内存分区测试
* @FilePath: \C++核心编程\1内存分区模型\1_2程序运行后.cpp
*/
#include <iostream>
using namespace std;
int *func();
int main(){
int *p = func();
cout << *p << endl;
system("pause");
return 0;
}
int *func()
{
//堆区数据利用new关键字进行开辟内存
int* a = new int(10);//利用new创建的数据,会返回该数据对应的类型的指针
return a;
}
1.3 new操作符_基本语法
/*
* @Author: Heweifu
* @Date: 2021-09-26 23:35:11
* @LastEditTime: 2021-09-26 23:43:30
* @LastEditors: Heweifu
* @Description: 12222
* @FilePath: \C++核心编程\1内存分区模型\1_3new操作符_基本语法.cpp
*/
#include <iostream>
using namespace std;
int *func();
int main()
{
int *p = func();
cout << *p << endl; //10
delete p; //堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符 ==delete==
cout << *p << endl; //释放后的指针为野指针,值不确定(Random)
system("pause");
return 0;
}
int *func()
{
int *a = new int(10);
return a;
}
1.3 new操作符_开辟数组
/*
* @Author: Heweifu
* @Date: 2021-09-26 23:40:24
* @LastEditTime: 2021-09-26 23:43:11
* @LastEditors: Heweifu
* @Description: 12222
* @FilePath: \C++核心编程\1内存分区模型\1_3new操作符_开辟数组.cpp
*/
#include <iostream>
using namespace std;
int main()
{
int *arr = new int[10];
for (int i = 0; i < 10; i++)
{
arr[i] = i + 10;
}
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl;
}
//释放数组 delete 后加 []
delete[] arr;
system("pause");
return 0;
}