How to dynamically allocate arrays in C++

前端 未结 5 751
日久生厌
日久生厌 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:53

    In C++ we have the methods to allocate and de-allocate dynamic memory.The variables can be allocated dynamically by using new operator as,

                         type_name *variable_name = new type_name;
    

    The arrays are nothing but just the collection of contiguous memory locations, Hence, we can dynamically allocate arrays in C++ as,

                         type_name *array_name = new type_name[SIZE];
    

    and you can just use delete for freeing up the dynamically allocated space, as follows, for variables,

                         delete variable_name;
    

    for arrays,

                         delete[] array_name;
    

提交回复
热议问题