代码之家  ›  专栏  ›  技术社区  ›  Sudantha

如何创建动态整数数组

c++
  •  64
  • Sudantha  · 技术社区  · 15 年前

    如何在C++中使用C++创建动态数组 new 关键词?

    6 回复  |  直到 12 年前
        1
  •  110
  •   Jason Iverson    15 年前
    int main()
    {
      int size;
    
      std::cin >> size;
    
      int *array = new int[size];
    
      delete [] array;
    
      return 0;
    }
    

    别忘了 delete 分配的每个数组 new .

        2
  •  58
  •   Ben Voigt    9 年前

    由于C++ 11,有一个安全的替代方案 new[] delete[] 这是零开销 std::vector :

    std::unique_ptr<int[]> array(new int[size]);
    

    在C++ 14中:

    auto array = std::make_unique<int[]>(size);
    

    #include <memory>

        3
  •  27
  •   jveazey    15 年前

    您可能需要考虑使用标准模板库。它简单易用,而且不必担心内存分配问题。

    http://www.cplusplus.com/reference/stl/vector/vector/

    int size = 5;                    // declare the size of the vector
    vector<int> myvector(size, 0);   // create a vector to hold "size" int's
                                     // all initialized to zero
    myvector[0] = 1234;              // assign values like a c++ array
    
        4
  •  4
  •   Ed Swangren    15 年前
    int* array = new int[size];
    
        5
  •  3
  •   carimus    10 年前

    memcpy ,您可以使用 memcpy_s std::copy 也。取决于编译器, <memory.h> 或 <string.h> 可能需要。使用此函数时,请分配新的内存区域,将原始内存区域的值复制到其中,然后释放它们。

    //    create desired array dynamically
    size_t length;
    length = 100; //for example
    int *array = new int[length];
    
    //   now let's change is's size - e.g. add 50 new elements
    size_t added = 50;
    int *added_array = new int[added];
    
    /*   
    somehow set values to given arrays
    */ 
    
    //    add elements to array
    int* temp = new int[length + added];
    memcpy(temp, array, length * sizeof(int));
    memcpy(temp + length, added_array, added * sizeof(int));
    delete[] array;
    array = temp;
    

    你可以用常数4代替 sizeof(int)

        6
  •  0
  •   SCBuergel    11 年前

    使用动态分配一些内存 new

    int* array = new int[SIZE];