I have written a function to read in a variable number of ints into an array, & after this is called I print out the values in the array that were read in in main(). When i print out the contents of the array however, most of f the elements are garbage and bear no resemblance to what values I entered in. I think the array it is modifing is not modifing the size for the calling function but I am not sure how to fix it as the function also returns the number of elements read into the array. The array has expected values inside the read function and returns the correct value for n. Here is code:
Code:
#include <iostream>
using namespace std;
void read(int *a, int &n);
// read the first n elements of array a
int SIZE = 5;
int main()
{
int *list1 = new int[SIZE];
int *list2 = new int[SIZE];
int noeles1=0, noeles2, test1, test2;
read(list1, noeles1);
read(list2, noeles2);
cout << "List 1: " << endl;
for (test1=0; test1<noeles1; test1++) {
cout << list1[test1];
cout << " ";
}
cout << "\nList 2: " << endl;
for (test2=0; test2<noeles2; test2++) {
cout << list2[test2];
cout << " ";
}
return 0;
}
// write the body of following functions
void read(int *a, int &n)
{
SIZE = 5;
int k;
cout << "Enter values:" << endl;
n=0;
do {
if (n<SIZE) cin >> a[n];
else {
SIZE *= 2; //double array
int *temp = new int[SIZE];
for (k = 0; k<SIZE; k++) temp[k] = a[k];
delete [] a;
a = temp;
cin >> a[n];
}
} while (a[n++] != -1);
n--;
}