Dynamic Array Allocation

I have just started working with pointers so bear with me. I was doing a side programming challenge in my workbook that asked me to dynamically allocate and array for test scores. So far I have an array that will accept an integer to allocate the amount of test scores and then will accept integers to populate the array, however when I try to cout the contents of the array the numbers are absurdly different than what was put in. Here's my code:
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
#include "stdafx.h"
#include <iostream>
using namespace std;


void main()
{

	cout << "How many test scores?" << endl;
	int scores(0);
	cin >> scores;

	int *ptr = nullptr;
	ptr = new int[scores];

	for(int count = 0; count < scores; count++)
	{
		cout << "Enter test score " << (count + 1) << ": " << endl;
		cin >> *ptr++;
	}

	for(int count = 0; count < scores; count++)
	{
		cout << *(ptr + count) << endl;
	}
}

And this is the output screen:
How many test scores?
4
Enter test score 1:
22
Enter test score 2:
33
Enter test score 3:
44
Enter test score 4:
55
-33686019
18472
55656634
201345063
Press any key to continue . . .
Why am I getting these crazy numbers? I've looked back and forth from examples in my book and it doesn't look like I'm doing anything wrong.
instead of using cin >> *ptr++ ... I just put cin >> ptr[count]

and cout << ptr[count]

there are other ways to access pointers and don't forget to free the memory at the end also...not sure if you can just say "delete ptr" and be done or if you have to iterate through each element in the new created array...but the above worked for me.
You can also make line 19 match how you've done it on line 24.

If you use new [], you need to deallocate with delete [].
Thanks. I actually got it working the way you described, however I still don't understand why the way I tried first won't work, because it seems like it should. I rewrote the output loop like this:
1
2
3
4
5
for(int count = 0; count < scores; count++)
	{
		cout << *ptr++ << endl;
		
	}

and that works just fine but for some reason
 
cin >> *ptr;

is still outputting weird numbers.
I think I am overwriting the bounds of the array
maybe because on the last pass of the loop it is incrementing ptr again?
or because you are moving the location of the ptr in the first loop and losing the starting position.

and i think " delete[] ptr " is what i was thinking
Last edited on
Topic archived. No new replies allowed.