c++ - C++ 中的动态数组(用指针表示)- 输入元素?

标签 c++ arrays pointers element

我有一个家庭作业任务,我应该创建一个数组并仅使用指针实现冒泡排序算法。我创建了数组,但是如果我想输入 3 元素,即如果用户输入 n = 3,程序不允许我输入第三个数字。我想问一下为什么会这样?

提前致谢。

#include <iostream>
using namespace std;
int *n = new int ;
int main()
{
    cout<<"Vavedete broya na chislata:"<<' ';
    cin>>*n;
    int *arr = new int[*n];
    cout<<"Vavedete elementite:"<<endl;
    int *i=new int;
    for(*i=0; *i<*n; *i++)
    {
        cin>>*(arr+*i);

    }
    return 0;
}

最佳答案

“*”和“++”运算符具有相同的优先级,但关联性是从右到左。您正在取消引用循环中未使用的 i++。 尝试:

#include <iostream>
using namespace std;
int *n = new int ;
int main()
{
    cout<<"Vavedete broya na chislata:"<<' ';
    cin>>*n;
    int *arr = new int[*n];
    cout<<"Vavedete elementite:"<<endl;
    int *i=new int;
    for(*i=0; *i<*n; (*i)++)
    {
        cin>>*(arr+*i);

    }
    return 0;
}

关于c++ - C++ 中的动态数组(用指针表示)- 输入元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48920060/

相关文章:

c++ - 为什么 bool 类型的二维数组不保存 0 和 1?

javascript - 当某些对象必须避免配对在一起时,如何将一个数组的元素随机映射到另一个数组的元素?

php - 在 PHP 中按对象 ID 对数组进行排序

arrays - Ruby 数组 += vs 推送

c++ - 打印转义字符

c++ - 选择排序不排序第一个值

c - 在不同的功能中分配的空闲内存?

c++ - 错误 : invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

char 和指针一起工作给出警告 : assignment from incompatible pointer type

c++ - 在 Visual Studio 2012 C++ 项目中嵌入 Python