【问题标题】:Enter elements into dynamic (pointer-defined) array in C++?在 C++ 中将元素输入到动态(指针定义)数组中?
【发布时间】:2018-02-20 12:19:59
【问题描述】:

我想问一个关于在动态数组中输入元素的问题。我声明了一个数组,然后我想在其中输入元素。如何使用指向我之前声明的数组 arr[] 的指针来执行此操作? 提前致谢!

#include <iostream>
#include <algorithm>
using namespace std;
int *n = new int ;
int main()
{

    cin>>*n;
    int *arr = new int[*n];

    int *i=new int;
    for(*i=0; *i<=*n; *i++)
    {
        //Here, I should enter the elements but I cannot figure out how?
        cin>>(*arr+i);

    }
    return 0;
}

【问题讨论】:

  • 您不需要大小指针或索引。也可以考虑使用std::vector
  • 您应该绝对投资一本好的 C++ 初学者书籍。这是糟糕的代码。
  • 避免using namespace std;,使用std::vector&lt;T&gt;而不是new T[],尽可能使用自动存储,更喜欢x[i]而不是*(x+i),如果你有那么多一元*运算符在你的代码中,你应该重新考虑你在做什么。

标签: c++ arrays pointers cin elements


【解决方案1】:

虽然我质疑您对数组大小指针的用法索引(它们应该分别是int n;int i = 0;),但您可以使用下标运算符,或在代码中:

cin >> arr[*i];

使用指针算术只是不清楚并且很难说出您的目标是什么(如果您想知道,正确的符号是*(arr+*i),这看起来很糟糕 IMO)。

附带说明,考虑使用std::vector 作为容器,这将使您的生活更轻松,并避免您不得不处理指针。 std::vector 的用法可能如下所示:

int main()
{
    std::vector<int> arr;

    for (int x; std::cin >> x;)
    {
        arr.push_back(x);
    }

    return 0;
}

这将避免您也不必询问用户std::vector 的大小,并允许他们继续输入元素,直到他们输入 EOF。

【讨论】:

    【解决方案2】:

    这里我根本没有改变你原来的方法,这样你就可以更清楚地理解指针的概念。如您所知,数组和指针地址计算完全相同。首先,您需要计算地址,然后取消引用它。你只需要像下面这样改变它:-

       cin>>*arr++;
    

    您还需要更改您的 for 循环,如下所示:-

    for(*i=0; *i<=*n; (*i)++)
    

    但现在在上述for 循环之后,您将面临问题。原因是在将每个元素存储在arr之后,我们增加了arr(arr++)的地址,所以for循环结束后arr现在指向最后一个元素(因为arr = arr+* n)。所以首先简单地尝试下面的代码:-

     cout<<*arr<<endl<<endl;
    

    如果您输入了五个数字,例如 0、1、2、3 和 4,上述语句将打印一些垃圾值,因为指针再增加一次。

    现在试试下面的:-

    arr--;// Now arr will point to last element i.e. 4
    cout<<*arr<<endl<<endl;
    

    因此,您还需要一个 int 指针,并且应该在其中存储 arr 的第一个地址,如下所示:-

    int *arr = new int[*n];//exactly after this line of code
    int *first = arr;   
    

    现在使用for 循环来打印数组:-

    arr = first; //pointing to the first eliment
    for(*i=0; *i<=*n; (*i)++)
    {
        //Here, I should enter the elements but I cannot figure out how?
        cout<<*arr++<<endl;
    }    
    

    【讨论】:

    • 第一个不完全。我知道这很奇怪,但他的 iint*
    • 你说得对,第一种方法适用于字符串。更正了它。谢谢:-)
    猜你喜欢
    • 2015-09-14
    • 2022-01-24
    • 2013-02-08
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    相关资源
    最近更新 更多