C++快速入门---动态数组(24)
编写一个程序为一个整数型数组分配内存,实现动态数组。能够在程序运行时让用户输入一个值,自行定义数组的长度。
新建一个动态数组
例如:
int *x = new int[10];
可以像对待一个数组那样使用指针变量x:
x[1] = 45;
x[2] = 8;
扫描二维码关注公众号,回复:
4134106 查看本文章
删除一个动态数组
delete []x;
#include <iostream>
#include <string>
int main()
{
unsigned int count = 0;
std::cout << "请输入数组的元素个数:\n";
std::cin >> count;
//在程序运行时,堆里面申请内存
int *x = new int[count];//数组名
for(int i = 0; i < count; i++)
{
x[i] = i;
}
for(int i = 0; i < count; i++)
{
std::cout << "x[" << i << "]的值是:" << x[i] << "\n";
}
return 0;
}