c++ - 为什么使用动态数组而不是常规数组?

标签 c++ dynamic-arrays

以下代码用于演示如何在动态数组中插入新值:

#include <iostream>

int main()
{
    int* items = new int[5] {1, 2, 3, 4, 5}; // I have 5 items

    for (int i = 0; i < 5; i++)
        std::cout << items[i] << std::endl;

    // oh, I found a new item. I'm going to add it to my collection.
    // I do this by
    // (1) allocating a bigger dynamic array
    // (2) copying the existing elements from the old array to the new array
    // (3) deleting the old array, redirecting its pointer to the new array
    int* items_temp = new int[6];
    for (int i = 0; i < 5; i++)
       items_temp[i] = items[i];
    items_temp[5] = 42;
    delete[] items;
    items = items_temp;

    for (int i = 0; i < 6; i++)
        std::cout << items[i] << std::endl;

    delete[] items;
}

我对在常规数组上使用它的必要性感到困惑。我不能对常规数组做同样的事情吗?基本上,您只需定义一个更大尺寸的新数组,并将前一个数组中的元素移动到这个新数组中。为什么这里使用动态数组更好?

最佳答案

你是对的,你正在看的例子并不能很好地证明动态数组的必要性,但是如果我们不知道我们找到了多少个项目,而不是从大小 5->6,该怎么办?需要添加直到代码实际运行吗?

需要使用编译时已知的大小来构造常规数组

int foo [5] = { 16, 2, 77, 40, 12071 };

但是动态数组可以在运行时指定大小

int* Arrary(int size) {
    return new int[size];
}

因此,如果您不知道数组的大小,或者可能需要增大/缩小,则需要使用动态数组(或者更好的是使用 std::vector) .

关于c++ - 为什么使用动态数组而不是常规数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69179378/

相关文章:

c++ - 从 C++ 到 Haskell 类和状态

c++ - 查找导致链接库函数的函数

c++ - 更改数组类以保存动态数组

安卓动态数组

c - stackInit 函数出现段错误,我不明白为什么

c - C 中的大型数组

c++ - 无法重定向程序的控制台输出

c++ - 确保具有全局范围的静态变量在任何地方都存在一次

c++ - char类型的参数* lpcwstr类型的参数

c++ - 函数中的动态二维数组分配并将其返回给主函数?