【问题标题】:Dynamic memory allocation and taking input动态内存分配和输入
【发布时间】:2020-07-22 05:01:06
【问题描述】:

我正在尝试获取用户输入并将其存储在动态分配的数组中。但看起来我离得到这个东西还很远。 我到底犯了什么错误?

#include<iostream>
#include<string>
using namespace std;

struct abc
{
    int x;
    int *y;
};

int main()
{
    abc d;
    d.y = new int[5];
    for(int i=0; i<5; i++)
    {
        //cin>>d.y->x; //Error//user_input
        cout<<"Address : "<<(d.y+i)<<endl;
    };
}

【问题讨论】:

    标签: c++ arrays pointers data-structures dynamic-arrays


    【解决方案1】:

    你需要像下面这样输入数组(abc.y)

    for (int i = 0; i < 5; i++)
    {
       cin >> d.y[i]; // like this
    };
    

    另外,不要忘记之后释放内存,否则内存泄漏。


    但是,我建议在此处使用 std::vector&lt;int&gt;smart pointer 而不是原始指针。

    另外请注意,如果将abc 复制到另一个,您需要实现自己的复制移动并需要其他构造函数(又名rule of three/five/zero)。

    【讨论】:

      【解决方案2】:

      我认为您的错误在注释行中?如果是这样,那么您可能想要的是 cin &gt;&gt; d.y[i]; 而不是 cin &gt;&gt; d.y-&gt;x; (甚至不应该编译)。 -&gt; 运算符与类和结构一起使用,以获取y 指向的对象中的x 成员。这不是你需要的。

      【讨论】:

        【解决方案3】:

        在您的情况下出现错误的原因是您没有将元素插入到分配数组的每个第 i 个元素中。 确保在使用后删除数组。我已经重新调整了一些内容,以便您在将元素插入数组后看到地址和值。

        #include<iostream>
        #include<string>
        using namespace std;
        
        struct abc
        {
            int x;
            int *y;
        };
        
        int main()
        {
            abc d;
            d.y = new int[5];
            for(int i=0; i<5; i++)
            {
                cin >> *(d.y+i); // same as cin >> d.y[i];
            }
            for (int i = 0; i < 5; i++) {
                cout<<"Address : " <<(d.y+i)<< ", value: " << *(d.y+i) << endl;
            }
            delete [] d.y;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-18
          • 1970-01-01
          • 1970-01-01
          • 2018-03-04
          • 1970-01-01
          • 1970-01-01
          • 2012-01-13
          • 2020-04-21
          相关资源
          最近更新 更多