記憶體磁區模型
- 1 代碼區
- 2 全域區
- 3 堆疊區
- 4 堆區
- 5 new運算子

1 代碼區


2 全域區
// 全域變數、靜態變數、常量

#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;//&a取地址,(int)強制轉換為10進制
cout << "區域變數b的地址為:" << (int)&b <<endl<<endl;
//全域變數
cout << "全域變數g_a的地址為:" << (int)&g_a << endl;
cout << "全域變數g_b的地址為:" << (int)&g_b << endl<<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 << endl;
//常量(字串常量、const修飾的變數)
//字串常量
cout << "字串常量的地址為:" << (int)&"hello word" << endl;
//const修飾的變數(全域常量、區域常量)
//const修飾的全域變數
cout << "全域常量 c_g_a的地址為:" << (int)&c_g_a << endl;
cout << "全域常量 c_g_b的地址為:" << (int)&c_g_b << endl;
//const修飾的區域變數
const int c_a = 10;
const int c_b = 10;
cout << "區域常量 c_a的地址為:" << (int)&c_a << endl;
cout << "區域常量 c_b的地址為:" << (int)&c_b << endl << endl;
system("pause");
return 0;
}


總結

3 堆疊區

//堆疊區注意事項
//不要回傳區域變數的地址
//堆疊區的資料由編譯器管理開辟和釋放
#include <iostream>
using namespace std;
//堆疊區注意事項
//不要回傳區域變數的地址
//堆疊區的資料由編譯器管理開辟和釋放
int *func(int b)//形參資料也存放在堆疊區
{
b = 100;
int a = 10;//區域變數:存放在堆疊區,堆疊區的資料在函式執行完畢自動釋放
return &a;//回傳區域變數的地址
}
int main()
{
//接受func函式的回傳值
int *p=func(1);
cout << *p << endl;//第一次可以列印正確的數字,因為編譯做了一次保留
cout << *p << endl;//第二次,就沒了,輸出亂碼
system("pause");
return 0;
}

4 堆區


#include <iostream>
using namespace std;
int *func()
{
//利用new關鍵字,將資料開辟到堆區
//指標本質也是區域變數,存放在堆疊上,指標保存的資料存放咋堆區
int* p = new int(10);
return p;
}
int main()
{
//在堆區開辟資料
int* q = func();
cout << *q << endl;//與上一個程式對比,多輸出幾次
cout << *q << endl;
cout << *q << endl;
cout << *q << endl;
system("pause");
return 0;
}

5 new運算子

#include <iostream>
using namespace std;
//1.new的基本語法
int* func()
{
//在堆區創建整形資料
//new回傳的是資料型別指標
int* p = new int(10);
return p;
}
//2.在堆區利用new 開辟陣列
int main()
{
//在堆區開辟資料
int* q = func();
cout << *q << endl;//與上一個程式對比,多輸出幾次
cout << *q << endl;
cout << *q << endl;
//堆區資料是由程式員管理開辟、管理釋放
//如果想釋放堆區資料,利用關鍵字delete
delete q;
cout << *q << endl;//記憶體已被釋放,再次訪問就是非法操作,報錯
system("pause");
return 0;
}


#include <iostream>
using namespace std;
//1.new的基本語法
//2.在堆區利用new 開辟陣列
void test()
{
//創建10整形資料的陣列,在堆區
int *arr =new int[10];//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()
{
test();
system("pause");
return 0;
}

注意:
釋放堆取陣列
釋放陣列的時候,要加[]才可以,否則認為是只是放一個元素
參考:
嗶哩嗶哩 黑馬程式員
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/279370.html
標籤:其他
上一篇:極客日報第109期:蘋果合作伙伴廣達遭黑客勒索 5000 萬美元;女子5年前打賭錘子手機破產贏一部iPhone;?安卓32位時代落幕
