我是 CPP 的新手。我正在尝试使用 pointer
和 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 :(";
}
输出是
我的代码有什么问题?
问候,
沙
最佳答案
循环内的 array++
递增指针,因此当您完成第一个循环时,array
将指向最初分配的数组之外。
就这样
cin >> *(array+index);
或者只是
cin >> array[index];
关于c++ - 带有 cin 实现问题的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14919998/