在翻阅我的作业时,我遇到了一个我无法弄清楚的错误。我已经阅读并玩过它,但我无法弄清楚我做错了什么。
用户输入int
指针数组,然后代码应该是数组大小的两倍,并使用0
填充新元素。问题是新元素不是0
。我做错了什么,打印的这些数字是什么,地址?
输出:
Enter array size: 3
Enter Element 0: 10
Enter Element 1: 11
Enter Element 2: 12
Entered Array:
Element 0/3 is 10
Element 1/3 is 11
Element 2/3 is 12
Resized Array:
Element 0/6 is 10
Element 1/6 is 11
Element 2/6 is 12
Element 3/6 is -33686019
Element 4/6 is 1196933248
Element 5/6 is 201354124
Press any key to continue . . .
代码:
#include <iostream>
#include <string>
using namespace std;
int *createArray(int size)
{
int *newArray;
newArray = new int[size];
for( int i = 0; i < size; i++){
cout << "Enter Element " << i << ": ";
cin >> newArray[i];
}
return newArray;
}
int *dblArraySize ( int *myArray, int& size)
{
int *newArray;
newArray = new int[size*2];
for (int i = 0; i < size; i++)
newArray[i] = myArray[i];
for (int i = size; i < size*2; i++){
newArray[i] = 0;
}
size = size*2;
return newArray;
}
void displayArray(int *anArray, int size, string msg)
{
cout <<endl << endl << msg;
for (int i = 0; i<size;i++){
cout << endl << "Element " << i << "/" << size << " is " << anArray[i];
}
}
int main ()
{
int size,
*mainArray;
cout << "Enter array size: ";
cin >> size;
mainArray = createArray(size);
displayArray(mainArray,size, "Entered Array:");
dblArraySize(mainArray,size);
displayArray(mainArray,size, "Resized Array:");
}
答案 0 :(得分:3)
问题是你从dblArraySize返回newArray,但从不使用它。你永远不会修改mainArray
dblArraySize(mainArray,size);
应该是:
mainArray = dblArraySize(mainArray,size);
另请注意:您忘记释放原始阵列的内存。