C++ 内存分区模型-静态存储区:

时间:2024-04-15 07:08:07

静态存储区内的变量在程序编译阶段已经分配好内存空间并初始化。这块内存在程序的整个运行期间都存在,它主要存放静态变量、全局变量和常量。

  • 静态存储区内的常量分为全局常量字符串常量,一经初始化,不可修改。局部常量存放于栈!!!!,其生命周期仅限于函数的执行过程。

#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;

//全局静态变量
static int g_s_a = 10;
static int g_s_b = 10;


int main() {


	cout << "********************************************" << endl;
	//局部变量
	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;





	cout << "********************************************" << endl;
	//局部静态变量
	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 << "全局静态变量s_a地址为: " << (int)&g_s_a << endl;
	cout << "全局静态变量s_b地址为: " << (int)&g_s_b << endl;


	cout << "********************************************" << endl;



	cout << "字符串常量地址为: " << (int)&"hello world" << endl;
	cout << "字符串常量地址为: " << (int)&"hello world1" << endl;




	cout << "********************************************"<< 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;

	cout << "全局常量c_g_a地址为: " << (int)&c_g_a << endl;
	cout << "全局常量c_g_b地址为: " << (int)&c_g_b << endl;

	system("pause");

	return 0;
}

在这里插入图片描述
全局区

  • 全局变量 静态变量(static) 全局常量(const) 字符串常量区 离得比较近

不在全局区

  • 局部常量 和 局部变量 比较近