【发布时间】:2014-03-22 05:30:56
【问题描述】:
我的程序以动态分配 (DA) 数组开始。然后它会提示用户输入尺寸。如果输入的大小在某个阈值之内,则创建一个新的 DA 数组,将旧数组的内容复制到新数组中,然后显示新数组。
我在将内容从一个动态 DA 数组复制到另一个动态分配数组时遇到问题。通过重新分配过程的每一步,我都有“打印测试”,在每个过程之后显示数组。我测试初始化和复制。
请看下面的代码。具体来说,如果我输入 27、28、29 或 70,我会得到一堆看起来像内存地址的奇怪数字....我不知道我做错了什么。
我不能使用向量。
编辑:天哪,非常感谢您指出我的错误……让我很困惑。再次感谢大家!!!
#include <iostream>
using namespace std;
int main () {
int maxSize = 25;
int active_size = 0;
int *uaptr;
uaptr = new int [maxSize];
for (int i=0; i<maxSize; i++)
*(uaptr + i) = 1;
cout << "\nWhat size you would like the array to be?: ";
cin >> active_size;
cin.clear();
cin.ignore (1000, 10);
if (active_size > (0.8 * maxSize)) {
maxSize *= 4;
int *tempPtr;
tempPtr = new int [maxSize];
for (int i=0; i<maxSize; i++)
*(tempPtr + i) = 0;
cout << "Testing initialization..." << endl;
for (int i=0; i<maxSize; i++) { //TEST INITIALIZATION
cout << *(tempPtr + i) << " ";
if ((i+1)%10==0)
cout << endl;
}
for (int i=0; i<active_size; i++) //Copy contents of old array into new,bigger array
*(tempPtr + i) = *(uaptr + i); //*****What is wrong here?!?!
cout << endl;
cout << "Testing the copying..." << endl;
for (int i=0; i<maxSize; i++) { //TEST COPYING -weird results when numbers 27, 28, 29 or 70 are entered
cout << *(tempPtr + i) << " ";
if ((i+1)%10==0)
cout << endl;
}
delete [] uaptr; //release old allocated memory
uaptr = tempPtr; //update the pointer to point to the newly allocated array
cout << endl;
for (int i = 0; i < active_size; i++) {
cout << *(uaptr + i) << " ";
if ((i + 1) % 10 == 0)
cout << endl;
}
}
}
【问题讨论】:
标签: c++ arrays dynamic-allocation