user1535963
user1535963

Reputation: 41

Array Pointer in C++

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

Answers (4)

Ed Heal
Ed Heal

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

mmmmmm
mmmmmm

Reputation: 32661

There are several issues here.

  1. You have nowhere to store the values. You have an array of 8 pointers which are all set to point to the same variable n, which is on the stack and so goes out of scope.
  2. The array has 8 elements so the loop goes one past the end
  3. This is C++ so really best not to use C arrays unless you have a justifiable reason to.

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

ryanbwork
ryanbwork

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

timos
timos

Reputation: 2707

You are saving a pointer to n in the array, but you constantly change the value of n.

Upvotes: 1

Related Questions