You have several problems with your code:
1. you are not allocating enough memory to be able to add an additional int to the array.
2. you input loop starts outside your allocated memory. Also, looping backwards to input your initial values will guarantee the first array element (numPtr[0]) will contain a garbage value. Obtaining your new value after printing out the initial array will merely overwrite the last array element.
3. you are incrementing outside your allocated memory with line 23.
4. How does your function
printArray()
know the size of your passed array?
5. The way you are passing your array into your function crashes after outputting the first array value.
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
|
#include <iostream>
void printArray(int* numPtr, int size);
int main()
{
int x;
std::cout << "Enter dynamic array size: ";
std::cin >> x;
int* numPtr = new int[x + 1];
std::cout << "Input contents of array:\n";
for (int i = 0; i < x; i++)
{
std::cin >> numPtr[i];
}
printArray(numPtr, x);
std::cout << "\nEnter new integer to append to array: ";
std::cin >> numPtr[x];
printArray(numPtr, x + 1);
delete[] numPtr;
}
void printArray(int* numPtr, int x)
{
for (int z = 0; z < x; z++)
{
std::cout << numPtr[z] << " ";
}
}
|
Unless this is a class assignment you really should use the STL containers,
std::vector
is good when needed a dynamic array.