Having problem with Dynamic Array!
Anyone please help! I do not know why I get strange output for the code I list below. please explain.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
typedef int* InterArrayPtr;
void getInput (int* array, int size, int sizeLager);
//Precondition:
//Postcondition:
int main() {
using namespace std;
int sizeNumber1(0), sizeNumber2(0);
InterArrayPtr array1 = new int[sizeNumber1];
InterArrayPtr array2 = new int[sizeNumber2];
cout << "Enter the size of the larger number: ";
cin >> sizeNumber1;
getInput(array1, sizeNumber1, sizeNumber1);
cout << "Enter the size of the second number: ";
cin >> sizeNumber2;
getInput(array2, sizeNumber2, sizeNumber1);
for (int i = 0; i < sizeNumber1; i++) {
cout << *(array1 + i) << " ";
}
cout << endl;
for (int i = 0; i < sizeNumber1; i++) {
cout << *(array2 + i) << " ";
}
cout << endl;
delete [] array1;
delete [] array2;
return 0;
}
void getInput (int *array, int size, int sizeLager) {
using namespace std;
if (sizeLager > size) {
int i = sizeLager - 1;
while (i >= size) {
array[i] = 0;
i--;
}
}
cout << "Enter number: ";
for (int i = size - 1; i >= 0; i--) {
cin >> array[i];
}
}
/*
Sample Dialouge:
Enter the size of the larger number: 5
Enter number: 1 2 3 4 5
Enter the size of the second number: 3
The i is: 4
Enter number: 1 2 3
5 4 3 2 3
3 2 1 0 0
Program ended with exit code: 0
*/
|
1 2 3
|
int sizeNumber1 (0), sizeNumber2 (0);
InterArrayPtr array1 = new int[sizeNumber1];
InterArrayPtr array2 = new int[sizeNumber2];
|
Why do you create an array with size 0 ?
@Thomas1965
But after fix that the program still run strange!
I think I already find out the problem! Thanks @Thomas1965
Topic archived. No new replies allowed.