C++中為什么要使用動態(tài)內(nèi)存
更新時間:2022年02月07日 10:41:47 作者:駱駝胡楊
大家好,本篇文章主要講的是C++中為什么要使用動態(tài)內(nèi)存,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下
為什么要使用動態(tài)內(nèi)存
1.按需分配,根據(jù)需要分配內(nèi)存,不浪費
int main(void) { int money[10] = { 1, 2, 3 ,4, 5, 6, 7, 8, 9, 10 }; //工錢 int len = sizeof(money) / sizeof(money[0]); //money數(shù)組的長度 int num = 20; //人數(shù) int *salary = 0; //薪資 //給salary指針分配num個內(nèi)存 salary = new int[num]; //方式一, 逐個賦值 /*for (int i = 0; i < len; i++) { *(salary + i) = money[i]; }*/ //方式二, 使用memcpy內(nèi)存拷貝 //memcpy(目標, 源數(shù)組, 數(shù)組的字節(jié)); memcpy(salary, money, sizeof(money)); for (int i = len; i < num; i++) { *(salary + i) = 666; //后面的元素全部賦值為666 } for (int i = 0; i < num; i++) { cout << "第" << i+1 << "個員工的薪資是: " << *(salary + i) << endl; } system("pause"); return 0; }
2.被調(diào)用函數(shù)之外需要使用被調(diào)用函數(shù)內(nèi)部的指針對應(yīng)的地址空間
#include <iostream> #include <Windows.h> #include <string.h> using namespace std; //方式一, 返回分配給指針的地址 int* copy1(int count) { int* ap = NULL; //malloc是C語言中的動態(tài)內(nèi)存分配操作符 ap = (int*)malloc(sizeof(int) * count); //new是C++中的動態(tài)內(nèi)存分配操作符 //ap = new int[count]; if (ap == NULL) { exit(1); } for (int i = 0; i < count; i++) { *(ap + i) = 100 + i; } return ap; //返回指針的地址 } //方式二, 使用二級指針 void copy2(int** ap, int len) { *ap = (int*)malloc(sizeof(int) * len); if (*ap == NULL) { exit(1); } for (int i = 0; i < len; i++) { *(*ap + i) = 100 + 1; } } int main(void) { int* p = NULL; //方式一, 接收copy1函數(shù)返回指針的地址 //p = copy1(10); //方式二, 使用二級指針 copy2(&p, 10); for (int i = 0; i < 10; i++) { cout << "第" << i+1 << "個員工的薪資是: " << *(p+ i) << endl; } //c 語言中的釋放內(nèi)存函數(shù),相當于 delete free(p); system("pause"); return 0; }
C 內(nèi)存分配: void *malloc(size_t size); // 分配內(nèi)存 void free(void *); // 釋放內(nèi)存 malloc 在內(nèi)存的動態(tài)存儲區(qū)中分配一塊長度為 size 字節(jié)的連續(xù)區(qū)域返回該區(qū)域的首地址.
3.突破棧區(qū)的限制,可以給程序分配更多的內(nèi)存
#include <iostream> #include <Windows.h> using namespace std; //棧區(qū)的空間大小是有限的, 在Windows系統(tǒng)中一般有 1-2 M的內(nèi)存 void demo1() { int a1[102400 * 2]; //100k * 2 * 4 = 800k //int a1[102400 * 3]; //100k * 3 * 4 = 1200k a1[0] = 1; cout << "This is a demo!" << endl; } //堆空間的大小是有限的, 在Windows10系統(tǒng)的限制是 2G void demo2() { int* p = NULL; p = (int*)malloc(1024 * 1000 * 1000 * 2); //大約2G p[0] = 1; cout << "This is a stack demo!" << endl; } int main(void) { //??臻g //demo1(); //堆空間 demo2(); system("pause"); return 0; }
到此這篇關(guān)于C++中為什么要使用動態(tài)內(nèi)存的文章就介紹到這了,更多相關(guān)C++動態(tài)內(nèi)存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言詳解如何應(yīng)用模擬字符串和內(nèi)存函數(shù)
這篇文章主要介紹了C語言詳解如何應(yīng)用模擬字符串和內(nèi)存函數(shù),文章有點長,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-02-02