在C ++中将元素输入到动态(指针定义)数组中?

时间:2018-02-20 12:19:59

标签: c++ arrays pointers cin elements

我想问一个关于在动态数组中输入元素的问题。我声明一个数组,然后我想在其中输入元素。如何使用我之前声明的数组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;
}

2 个答案:

答案 0 :(得分:0)

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

   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;
}    

答案 1 :(得分:0)

虽然我质疑你对数组指数大小的指针的使用情况(它们应该分别是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之前继续输入元素。