指针与cin实现问题

时间:2013-02-17 10:11:16

标签: c++

我是CPP的新成员。我正在尝试使用pointercin组合,这会产生奇怪的结果。

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 :(";
}

输出是

enter image description here

我的代码有什么问题?

的问候,

2 个答案:

答案 0 :(得分:3)

循环内的array++会增加指针,所以当你完成第一个循环时,array将指向最初分配的数组之外。

只做

cin >> *(array+index);

或只是

cin >> array[index];

答案 1 :(得分:1)

您正在推进第一个循环中的指针array

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) << ",";
}
相关问题