How to dynamically allocate arrays in C++

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

    you allocate memory using the new operator and release a pointer using delete operator. Note that you can't delete normal variables, only pointers and arrays can be deleted after accomplishing their task.

    int * foo;
    foo = new int [5];
    delete[] foo;
    

    a complete program

    #include 
    #include 
    using namespace std;
    
    int main ()
    {
      int i,n;
      int * p;
      cout << "How many numbers would you like to type? ";
      cin >> i;
      p= new (nothrow) int[i];
      if (p == nullptr)
        cout << "Error: memory could not be allocated";
      else
      {
        for (n=0; n> p[n];
        }
        cout << "You have entered: ";
        for (n=0; n

    result

    How many numbers would you like to type? 5
    Enter number : 75
    Enter number : 436
    Enter number : 1067
    Enter number : 8
    Enter number : 32
    You have entered: 75, 436, 1067, 8, 32,
    

提交回复
热议问题