【问题标题】:How to properly assigning a dynamically create an int and assign it to a dynamic array array with values?如何正确分配动态创建 int 并将其分配给具有值的动态数组数组?
【发布时间】:2018-04-28 20:00:38
【问题描述】:

我正在为我的 c++ 类进行分配,我需要从另一个指针动态分配一个新的 int、数组和指针来练习动态内存分配。

起初,我正在努力创建一个新的 int 来为我的新数组提供一个 int,但我得到了它的编译并且想知道我的声明是否正确。

int *dmaArray = new int;
*dmaArray = 4;

然后我把它放入一个动态创建的数组中,但我不知道如何声明数组的值,因为它错误地说“无法转换为 int”。我做了一些思考,我相信这是因为它被声明了,需要在声明时进行初始化;我不能,因为声明本身已经是一个声明(新)。

int * nodeValues = new int[*dmaArray];
nodeValues[*dmaArray] = {6, 2, 28, 1};

之后循环将无法分配值,因为值不是连续的或任何模式。 (好吧,无论如何,我需要使用数组,因为作业是这样说的。

【问题讨论】:

  • 您的代码非常混乱。他们不应该在课堂上告诉你如何做到这一点吗?
  • 你有一些基本的理解问题。我建议通过good book

标签: c++ loops dynamic-programming dynamic-memory-allocation


【解决方案1】:

这不是声明dynamic array并初始化它的方法:

int * nodeValues = new int[*dmaArray];
nodeValues[*dmaArray] = {6, 2, 28, 1};

所以你这样声明:

int* nodeValues = new int[dmaArray];

并使用循环或手动为其赋值:

nodeValues[0] = 6;
nodeValues[1] = 2;
nodeValues[2] = 28,
nodeValues[3] = 1;

请记住,数组使用索引来读取/写入其元素,因为事实上是某种类型的相同类型的数据在内存中彼此相邻。

所以如果要打印数组:

for(auto i(0); i != dmaArray; ++i)
    std::cout << nodeValues[i] << ", ";

最后你应该在完成后清理动态分配的内存,因为编译器不会为你做这件事:

delete[] nodeValues;

【讨论】:

  • 将大括号添加到末尾,其中包含一些工作原理 (int * nodeValues = new int[*dmaArray]{6,5,28,1};)
  • 你的`int[*dmaArray]`是什么意思?
【解决方案2】:

我想通了:

int * nodeValues = new int[*dmaArray]{6,5,28,1};

【讨论】:

    猜你喜欢
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2021-01-18
    相关资源
    最近更新 更多