/*
* Chapter 14
*
*
*
*
*/
#include <iostream>
usingnamespace std;
int* growArray(int* p_values, int* size);
void printArray(int* p_values, int size, int elements_set);
int main()
{
int next_element = 0;
int size = 10;;
int* p_values = newint[size];
int val;
cout << "Please enter a number: ";
cin >> val;
while (val > 0)
{
if (size == next_element + 1)
{
p_values = growArray(p_values, &size);
}
p_values[next_element] = val;
next_element++;;
cout << "Current array values are: " << endl;
printArray(p_values, size, next_element);
cout << "Please enter a number (or 0 to exit): ";
cin >> val;
}
delete[] p_values;;
}
void printArray(int* p_values, int size, int elements_set)
{
cout << "The total size of the array is: " << size << endl;
cout << "Number of slots set so far: " << elements_set << endl;
cout << "Values in the array: " << endl;
for (int i = 0; i < elements_set; i++)
{
cout << "p_values[" << i << "] = " << p_values[i] << endl;
}
}
int* growArray(int* p_values, int* size)
{
*size *= 2;
int* p_new_values = newint[*size];
for (int i = 0; i < *size; i++)
{
p_new_values[i] = p_values[i]; // The first pass through the
// function the size of p_values
// is 10. Yet, the for loop
// cycles 20 times. Why no
// compiler error? Is there a
// possible memory conflict
// where, say p_values[18],
// is occupied by another variable?
}
delete[] p_values;
return p_new_values;
}
At line 53, lets assume that p_values has 10 entries and *size is 10.
At line 55, you modify *size so that it is now 20. p_values still has only 10 entries.
Line 56, You're using *size (which now contains 20) as the termination condition of your loop, so your loop will execute 20 times. However, p_array still only has 10 entries. What do p_array[10]-[19] contain? Probably garbage, if they don't cause your program to crash.