Help Outputting Dynamic Array

I am trying to write a program in which the user enters the size of a dynamic array, then enters in the contents of the array, outputs the array through a separate function, and then enters another integer to concatenate onto the end of the array and outputs it again through the function. The numbers output by the array are incorrect. I'd greatly appreciate it if someone could help me fix it. Thank you!

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
#include <iostream>

using namespace std;

void printArray(int* numPtr[]);

int main()
{
	int x;
	cout << "Enter dynamic array size" << endl;
	cin >> x;
	int* numPtr = new int[x];

	cout << "Input contents of array" << endl;

	for (int i = x; i > 0; i--)
	{
		cin >> numPtr[i];
	}

	printArray(&numPtr);

	x++;

	cout << "Enter new integer to append to array" << endl;
	cin >> numPtr[x];
	printArray(&numPtr);


	delete[] numPtr;
}

void printArray(int* numPtr[])
{
	for (int z = 0; z < x; z++)
	{
		cout << *numPtr[z];
	}
}
closed account (E0p9LyTq)
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.
Last edited on
Topic archived. No new replies allowed.