shanxi建設(shè)銀行網(wǎng)站首頁seo全國最好的公司
1、內(nèi)存分區(qū)模型
C++程序在執(zhí)行時,將內(nèi)存大方向劃分為4個區(qū)域:
- 代碼區(qū):存放函數(shù)體的二進制代碼,由操作系統(tǒng)進行管理的
- 全局區(qū):存放全局變量和靜態(tài)變量以及常量
- 棧區(qū):編譯器自動分配釋放,存放函數(shù)的參數(shù)值,局部變量等
堆區(qū):由程序員分配和釋放,若程序員不釋放,程序結(jié)束時由操作系統(tǒng)回收
2、代碼區(qū)
- 存放CPU執(zhí)行的機器指令
- 代碼區(qū)共享的目的是對于頻繁被執(zhí)行的程序,只需要在內(nèi)存中有一份代碼即可
- 代碼區(qū)只讀使其只讀的原因是防止程序意外地修改了它的指令
3、全局區(qū)
- 全局變量靜態(tài)變量字放在此
- 全局區(qū)還包含了常量區(qū)字符串常量其他常量已存放在此
- 該區(qū)域的數(shù)據(jù)在程序結(jié)束后由操作系統(tǒng)釋放
全局變量、靜態(tài)變量、字符串常量、const修飾的全局變量
#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() {//創(chuàng)建普通局部變量int a = 10;int b = 10;cout << "局部變量a的地址為:" << (int) & a << endl;cout << "局部變量b的地址為:" << (int) & b << endl;cout << "全局變量a的地址為:" << (int)&g_a << endl;cout << "全局變量b的地址為:" << (int)&g_b << endl;//靜態(tài)變量static int s_a = 10;static int s_b = 10;cout << "靜態(tài)變量a的地址為:" << (int)&s_a << endl;cout << "靜態(tài)變量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; //g:global全局 c:local局部、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; }
![]()
4、棧區(qū)
由編譯自動分配釋放,存放函數(shù)的參數(shù)值,局部變是等。
注意事項:不要返回局部變量的地址,棧區(qū)開辟的數(shù)據(jù)由編譯器自動釋放
形參、局部變量
#include <iostream> using namespace std;int* func(int b) {//形參數(shù)據(jù)也會放在棧區(qū)b = 100;int a = 10;//局部變量 存放在棧區(qū), 棧區(qū)數(shù)據(jù)在函數(shù)執(zhí)行完后自動釋放return &a;//返回局部變量的地址 }int main() {int* p = func(1);cout << *p << endl;//第一次可以打印正確的數(shù)字,是因為編譯器做了保留cout << *p << endl;//第二次這個數(shù)據(jù)就不在保留system("pause");return 0; }
5、堆區(qū)
由程序員分配釋放,若程序員不釋放,程序結(jié)束時由操作系統(tǒng)回收
在C++中主要利用new在堆區(qū)開辟內(nèi)存
#include <iostream> using namespace std;int* func() {//利用new關(guān)鍵字 可以將數(shù)據(jù)開辟到堆區(qū)int *p=new int(10);return p; }int main() {int* p = func();cout << *p << endl;system("pause");return 0; }
6、new運算符
#include <iostream> using namespace std;//1、new的基本語法 int* func() {//在堆區(qū)創(chuàng)建整型數(shù)據(jù)//new返回是 該數(shù)據(jù)類型的指針int* p = new int(10);return p; }void test01() {int* p = func();cout << *p << endl;cout << *p << endl;cout << *p << endl;//堆區(qū)的數(shù)據(jù),由程序員管理開辟,程序員管理釋放//如果想釋放堆區(qū)的數(shù)據(jù),利用關(guān)鍵字deletedelete p;//cout << *p << endl;//內(nèi)存已經(jīng)被釋放,再次訪問就是非法操作,會報錯 }//2、在堆區(qū)利用new開辟數(shù)組 void test02() {//創(chuàng)建10個整型數(shù)據(jù)的數(shù)組,在堆區(qū)int*arr=new int[10];//10代表數(shù)組有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;}//釋放堆區(qū)數(shù)組//釋放數(shù)組的時候,要加[]才可以delete[] arr; }int main() {test01();test02();system("pause");return 0; }