【发布时间】:2017-10-09 21:01:59
【问题描述】:
使用动态内存,我正在尝试创建一个将数字存储在动态数组中的类(因此 123 将是 arr[0] = 1,arr[1] = 2,arr[2] = 3)并且能够追加数字(例如,如果存储的数字是 123,您可以添加更多数字.. 45,新数字将是 12345)。
到目前为止,这是我的代码:我将如何制作附加函数?
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int *exampleArray; //new array into exsistence
exampleArray = new int[5]; // dynamically allocates an array of 5 ints
for (int i = 1; i < 5; i++)
{
exampleArray[i] = i;
cout << exampleArray[i] << endl;
}
delete exampleArray; // deleted from exsistence
system("pause"); // to show the output
return 0;
}
【问题讨论】:
-
“追加”是什么意思?您打算在哪里添加数字?考虑检查当前分配的大小是否足够并调整大小+复制数组。甚至更好 - 使用
std::vector<int>而不是动态的int数组 -
不能保证额外的内存分配会在原始数组的末尾分配内存。
-
使用
std::vector<int>怎么样?? -
对数组进行扩展或追加的过程,是1)动态分配一个new更大的数组; 2) 将旧元素复制到新数组中; 3)删除旧数组。我们中的许多人更喜欢使用
std::vector,它为我们做这件事。
标签: c++ arrays dynamic-memory-allocation