Writing to an array using cin

Hi,

I'm trying to use cin to write to an array and then simply output that array by passing it to a function. See below

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
#include "stdafx.h"
#include <iostream>

void PrintArray(int *pArray, int nSize)
{
	using namespace std;
	for (int iii = 0; iii < nSize; iii++)
	{
		cout << pArray[nSize] << " ";
	}
}

int main()
{
	using namespace std;
	int nSize;
	cout << "Please enter the size of your array: \n";
	cin >> nSize;
	int *anArray = 0;
	anArray = new int [nSize];

	for (int iii = 0; iii < nSize; iii++) 
	{
		anArray[iii] = 0;    
	}

	for (int jjj = 0; jjj < nSize; jjj++)
	{
		if (jjj == 0)
			cout << "Please enter first array value: \n";
		else
			cout << "Please enter next array value: \n";
		
		cin >> anArray[jjj];
	}
		PrintArray(anArray, nSize);

		delete[] anArray;
		anArray = NULL;

		return 0;
}


I receive the following in the console window:

Please enter the size of your array:
2
Please enter first array value:
3
Please enter next array value:
4
-33686019 -33686019 Press any key to continue . . .

Can someone help me out please?
In your PrintArray function you have cout << pArray[nSize] << " "; where you really want cout << pArray[iii] << " ";
You are printing the same element over an over again.
Besides that, that element does not exist, you are trying to access out of bounds
7
8
9
10
	for (int iii = 0; iii < nSize; iii++)
	{
		cout << pArray[nSize] << " "; //nSize is out of bounds
	}
Last edited on
grrrr thank you! Stupid mistake!
Topic archived. No new replies allowed.