2013-02-17 57 views
0

我是CPP的新手。我试图使用pointercin组合,这给了奇怪的结果。cin执行问题的指针

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

什么我的代码的问题?

问候,

回答

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) << ","; 
} 
+0

非常感谢。有什么方法可以使指针在第一个循环后再次指向第一个位置? – sha 2013-02-17 10:19:42

+1

减去'numOfElem',因为你正在向它添加'numOfElem'。 – 2013-02-17 10:21:05

3

array++内循环递增指针,所以,当你正在与第一循环中完成的时候,array将原先分配的阵列外点。

只是做

cin >> *(array+index); 

或者干脆

cin >> array[index]; 
+0

谢谢。它也解决了。 :) – sha 2013-02-17 10:39:06