Pointers

I am suppose to design a program using pointers that dynamically stores and then prints the user input. I keep getting an error when I run it. Can anyone help?

Example Print:
Enter number of integers: 5
Enter integers: -3 -4 6 7 23 <--- suppose to print something like this
You entered: -3 -4 6 7 23

My Code:

#include <iostream>
using namespace std;

int main(){

int *dynArray; // pointer to the dynamically allocated array
int size; // array size

cout << "Enter number of integers: ";
cin >> size;

cout << "Enter integers: ";
cin >> dynArray[size];

cout << "You entered: " << *dynArray << endl;


}
int *dynArray; // pointer to the dynamically allocated array
This pointer has not been initialized; it contains a garbage value and points to random memory.

cin >> dynArray[size];
This asks the user to input ONE NUMBER to the address dynArray+size, which, evene if dynArray were valid, would be incorrect. This also means you are overwriting arbitrary memory that does not belong to you.

cout << "You entered: " << *dynArray << endl;
This says to output the integer at the address that dynArray points to, which is just random memory.

Consider:
Initialize dynArray with new: dynArray = new int[size];
Loop through i=0 to < size, inputting to dynArray[i]
Loop through i=0 to < size, outputting dynArray[i]
int size; // array size
int *dynArray = new int[size]; <-- this line is saying size hasn't been inititalized?

cout << "Enter number of integers: ";
cin >> size;

cout << "Enter integers: ";
for(int i=0; i < size; dynArray[i])
cin >> dynArray[i];
cout << "You entered: " << dynArray[i] << endl; <--right here says i is undefined


}
For that size error, you have to ask the user for the size before you initialize dynArray.
Thanks so much! That did fix the problem! The only problem I'm having now is getting all of the users numbers to print out. I'm only getting the first number to print out. Can anyone help me find the problem? My exact code is below.

#include <iostream>
using namespace std;

int main(){

int *dynArray; // pointer to the dynamically allocated array
int size; // array size

cout << "Enter number of integers: ";
cin >> size;
dynArray = new int [size];

cout << "Enter integers: ";
cin >> *dynArray;

cout << "You entered: " << *dynArray << endl;
for(int i=0; i < size; dynArray[i])
cin >> dynArray[i];

}
Last edited on
OK, I just went and ran through the code to see what's up. First, the reason why it continues to ask is because the for loop for entering the integers:
 
for(int i=0; i < size; dynArray[i])

should be:
 
for(int i = 0; i < size; i++)


and when recalling what the user entered, I would suggest this:
1
2
3
4
5
6
7
cout << "You Entered:";
	for(int i = 0; i < size; i++)
	{
		cout << dynArray[i] << " ";
	}
	cout << endl;
	return 0;


Hope this helps.
Last edited on
Yes thank you so much for your help! I really appreciate it!
Topic archived. No new replies allowed.