Reputation: 41
int n;
int *array[8]
cout<<"Enter Number Between 0-9 Only"<<endl;
for(int i = 0; i< 9; i++){
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array[i] = &n;
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
cout << *array[0] << endl;
}
I'm trying to store 9 entered numbers in a pointer array but its not working why?? Can you explain why to me and how to solve it or improve it. I'm just a beginner and its not homework im testing what i had read.
Upvotes: 0
Views: 189
Reputation: 59997
The line
array[i] = &n;
will store the same address in every entry in your array. This is just pointing to n
so will always point to that value.
Either define the array as an array of integers
i.e. int array[9];
and then place the value into that array
i.e. array[i] = n;
OR
Allocate some memory off the heap
i.e.
int *array[9];
...
array[i] = new int;
*array[i] = n;
But you will then have to free this memory with delete
to avoid a memory leak.
Upvotes: 4
Reputation: 32661
There are several issues here.
I would have something more like *NB not compiled and run)
{
...
std::vector<int> array;
cout<<"Enter Number Between 0-9 Only"<<endl;
for(int i = 0; i< 8; i++){
int n;
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array.push_back(n);
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
cout << array[0] << endl;
}
Upvotes: 2
Reputation: 2153
You don't really need to mess with pointers here. Change your array definition, how you populate it, and how you display and you should have better luck.
int array[9];
...
array[i] = n;
...
cout << array[0] << endl;
Upvotes: 0
Reputation: 2707
You are saving a pointer to n in the array, but you constantly change the value of n.
Upvotes: 1