Commit fff4c471 authored by Administrator's avatar Administrator
Browse files

add memory allocation

parent 4a2d4784
#include <iostream>
using namespace std;
int main() {
cout << "----- Variable memory allocation -----" << endl;
// 基础变量的内存分配
// 初始化为 null 的指针
double * pvalue = NULL;
// 为变量请求内存
if(!(pvalue = new double)) {
// 如果自由存储区已被用完,可能无法成功分配内存。
cout << "Error: out of memory." <<endl;
exit(1);
}
// 在分配的地址存储值
*pvalue = 29494.99;
cout << "Value of pvalue : " << *pvalue << endl;
// 释放 pvalue 所指向的内存
delete pvalue;
cout << "----- 2D array memory allocation -----" << endl;
// 二维数组的内存分配
int ROW = 2;
int COL = 3;
// 为行分配内存
double ** p2dArray = new double * [ROW];
double ** currRowPtr;
double * currColPtr;
// 为列分配内存
for(int i = 0; i < ROW; i++) {
p2dArray[i] = new double[COL];
}
// 指向起始位置
currRowPtr = p2dArray;
// 循环行
for (int i = 0; i < ROW; i++) {
cout << "Pointer of row[" << i << "] is: [";
cout << *currRowPtr << "] at [" << currRowPtr << "]" << endl;
// 循环列
currColPtr = *currRowPtr;
for (int j = 0; j < COL; j++) {
cout << "Pointer of col[" << j << "] is: [";
cout << *currColPtr << "] at [" << currColPtr << "]" << endl;
currColPtr++;
}
currRowPtr++;
}
// 释放内存,释放的时候,需要确保指针指向的位置是已经被分配过的
// 否则会出异常pointer being freed was not allocate
// delete * p2dArray;
// delete * currRowPtr;
// delete currColPtr;
cout << "----- Object memory allocation -----" << endl;
// 对象的内存分配
class Box {
public:
Box() {
cout << "调用构造函数!" <<endl;
}
~Box() {
cout << "调用析构函数!" <<endl;
}
};
Box * myBoxArray = new Box[4]; //
Box * currBox = myBoxArray;
for (int i = 0; i < 4; i++) {
cout << "Pointer of myBoxArray[" << i << "] at [" << currBox << "]" << endl;
currBox++;
}
delete [] myBoxArray;
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment