九.动态内存分配(从C到C++)

内容参考于《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,直接内存报错,大家可以试试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值