How to dynamically allocate arrays in C++

前端 未结 5 748
日久生厌
日久生厌 2020-12-16 06:30

I know how to dynamically allocate space for an array in C. It can be done as follows:

L = (int*)malloc(mid*sizeof(int)); 

and the memory c

5条回答
  •  失恋的感觉
    2020-12-16 06:56

    Following Info will be useful : Source : https://www.learncpp.com/cpp-tutorial/6-9a-dynamically-allocating-arrays/

    Initializing dynamically allocated arrays

    If you want to initialize a dynamically allocated array to 0, the syntax is quite simple:

    int *array = new int[length]();
    

    Prior to C++11, there was no easy way to initialize a dynamic array to a non-zero value (initializer lists only worked for fixed arrays). This means you had to loop through the array and assign element values explicitly.

    int *array = new int[5];
    array[0] = 9;
    array[1] = 7;
    array[2] = 5;
    array[3] = 3;
    array[4] = 1;
    

    Super annoying!

    However, starting with C++11, it’s now possible to initialize dynamic arrays using initializer lists!

    int fixedArray[5] = { 9, 7, 5, 3, 1 }; // initialize a fixed array in C++03
    int *array = new int[5] { 9, 7, 5, 3, 1 }; // initialize a dynamic array in C++11
    

    Note that this syntax has no operator= between the array length and the initializer list.

    For consistency, in C++11, fixed arrays can also be initialized using uniform initialization:

    int fixedArray[5] { 9, 7, 5, 3, 1 }; // initialize a fixed array in C++11
    char fixedArray[14] { "Hello, world!" }; // initialize a fixed array in C++11
    

    One caveat, in C++11 you can not initialize a dynamically allocated char array from a C-style string:

    char *array = new char[14] { "Hello, world!" }; // doesn't work in C++11
    

    If you have a need to do this, dynamically allocate a std::string instead (or allocate your char array and then strcpy the string in).

    Also note that dynamic arrays must be declared with an explicit length:

    int fixedArray[] {1, 2, 3}; // okay: implicit array size for fixed arrays
    
    int *dynamicArray1 = new int[] {1, 2, 3}; // not okay: implicit size for dynamic arrays
    
    int *dynamicArray2 = new int[3] {1, 2, 3}; // okay: explicit size for dynamic arrays
    

提交回复
热议问题