sha
sha

Reputation: 1420

Pointer with cin implementation issue

I'm a new bie to CPP. I'm trying to use pointer and cin combination which is giving strange result.

int *array;
int numOfElem = 0;
cout << "\nEnter number of  elements in array : ";  
cin  >> numOfElem;
array = new (nothrow)int[numOfElem];

if(array != 0)
{
    for(int index = 0; index < numOfElem; index++)
    {
        cout << "\nEnter " << index << " value";
        cin >> *array++;
    }

    cout << "\n values are : " ;
    for(int index = 0; index < numOfElem; index++)
    {
        cout << *(array+index) << ",";
    }
}else
{
    cout << "Memory cant be allocated :(";
}

The out put is

enter image description here

What the problem with my code ?

Regards,
Sha

Upvotes: 0

Views: 100

Answers (2)

Alexey Frunze
Alexey Frunze

Reputation: 62058

You are advancing the pointer, array, in the first loop:

for(int index = 0; index < numOfElem; index++)
{
    cout << "\nEnter " << index << " value";
    cin >> *array++;
}

And then you pretend you are using the original, unmodified pointer in the second loop:

cout << "\n values are : " ;
for(int index = 0; index < numOfElem; index++)
{
    cout << *(array+index) << ",";
}

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258608

The array++ inside the loop increments the pointer, so by the time you're done with the first loop, array will point outside the originally allocated array.

Just do

cin >> *(array+index);

or simply

cin >> array[index];

Upvotes: 3

Related Questions