c++ - 带有 cin 实现问题的指针

标签 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

我的代码有什么问题?

问候,

最佳答案

循环内的 array++ 递增指针,因此当您完成第一个循环时,array 将指向最初分配的数组之外。

就这样

cin >> *(array+index);

或者只是

cin >> array[index];

关于c++ - 带有 cin 实现问题的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14919998/

相关文章:

c++ - Qt+VS2010 - 无法解析的外部符号LNK2001

C++多重定义错误

c++ - 在 python 中导入 C++ 类?

c++ - 我可以检索包含非拉丁字符的路径吗?

c++ - 重载三元? : operator, 或更改为包含文件中的 if{}else{}

c++ - 我在从 .txt 文件中添加数字时遇到了一些问题

c++ - "::"中的 "::tolower"是什么意思?

c++ - 我可以在 C++ 中的 if 语句中使用 switch case 吗

java - Java 中的指针、 vector 和迭代器

c++ - tensorflow :转置需要一个大小为 1 的 vector 。但输入(1)是一个大小为 2 的 vector