C++ : Creating an array with a size entered by the user

后端 未结 3 577
不知归路
不知归路 2020-12-01 20:36

I was wondering if we can make an array with a size specified by the user.

Ex:

int a;
cout<<\"Enter desired size of the array\";
cin>>a;
         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 20:56

    Using dynamic allocation

    More on dynamic memory in C++

    #include 
    
    int main() {
        int size;
        std::cout <<"Enter desired size of the array";
        std::cin >> size;
        int *array = new int[size];
    }
    

    As mentioned in the linked article above:

    In most cases, memory allocated dynamically is only needed during specific periods of time within a program; once it is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of operator delete.

    When you're done with array you should delete it using the following syntax:

    delete[] array; 
    

    Using std::vector

    More on vectors

    #include 
    #include 
    
    int main() {
        int size;
        std::cout <<"Enter desired size of the array";
        std::cin >> size;
        std::vector array(size);
    }
    

提交回复
热议问题