内容参考于《21天学通C++》(第八版)
九.动态内存分配
1. 示例1
#include <iostream>
using namespace std;
int main()
{
// Request for memory space for an int
int* pointsToAnAge = new int;
// Use the allocated memory to store a number
cout << "Enter your dog’ s age: ";
cin >> *pointsToAnAge;
// use indirection operator* to access value
cout << "Age " << *pointsToAnAge << " is stored at 0x" << hex << pointsToAnAge << endl;
delete pointsToAnAge; // release memory
return 0;
}
运行结果
Enter your dog’ s age: 20
Age 20 is stored at 0x00EBDA18
第 6 行运算符 new 请求为一个整型分配内存,而您打算使用它来存储用户输入的小狗年龄。 New返回一个指针,因此将其赋给了一个指针变量。第 10 行使用 cin 和解除引用运算符( *)将用户输入的年龄存储在新分配的内存中。第13 行使用解除引用运算符( *)显示存储的值,还显示了内存的地址。在第 13 行, pointsToAnAge 包含的地址与第 6 行的 new 返回的地址相同,这个地址始终未变。
1. 示例2
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How many integers shall I reserve memory for?" << endl;
int numEntries = 0;
cin >> numEntries;
int* myNumbers = new int[numEntries];
cout << "Memory allocated at: 0x" << myNumbers << hex << endl;
// de-allocate before exiting
delete[] myNumbers;
return 0;
}
运行结果
How many integers shall I reserve memory for?
100.
Memory allocated at: 0x01180E40
我第一次测试这份代码,手收欠抽,输入了个99999999,直接内存报错,大家可以试试。