Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
Node is saved as draft in My Content >> Draft
  • Dynamic memory in C++

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 63
    Comment on it

    The allocation of memory is the crucial factor for any application.

    We allocate memory for variables and objects.

     

    We can perform memory allocation in the following two ways:

    • The stack: All variable declared inside will take memory from stack.

    • The heap: This will perform the allocation of memory when the program executes.

    We have data type which will allocate the memory at runtime. The new keyword is used for it.

     

    double* pvalue  = NULL; // Pointer initialized with null
    pvalue  = new double;   // Request memory for the variable

     

    double* pvalue  = NULL;
    if( !(pvalue  = new double ))
    {
       cout << "Error: out of memory." <<endl;
       exit(1);
    
    }

     

     

    Dynamic Memory Allocation for Arrays:

     

    char* pvalue  = NULL;   // Pointer initialized with null
    pvalue  = new char[20]; // Request memory for the variable

     

    Dynamic Memory Allocation for Objects:

     

    #include <iostream>
    using namespace std;
    
    class Box
    {
       public:
          Box() { 
             cout << "Constructor called!" <<endl; 
          }
          ~Box() { 
             cout << "Destructor called!" <<endl; 
          }
    };
    
    int main( )
    {
       Box* myBoxArray = new Box[4];
    
       delete [] myBoxArray; // Delete array
    
       return 0;
    }

     

    .net

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: