© Slobodan Dmitrović 2020
S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6047-0_22

22. Exercises

Slobodan Dmitrović1 
(1)
Belgrade, Serbia
 

22.1 Automatic Storage Duration

Write a program that defines two variables of type int with automatic storage duration (placed on the stack) inside the main function scope.
#include <iostream>
int main()
{
    int x = 123;
    int y = 456;
    std::cout << "The values with automatic storage durations are: " << x << " and " << y;
}

22.2 Dynamic Storage Duration

Write a program which defines a variable of type int* which points to an object with dynamic storage duration (placed on the heap) :
#include <iostream>
int main()
{
    int* p = new int{ 123 };
    std::cout << "The value with a dynamic storage duration is: " << *p;
    delete p;
}

Explanation

In this example, the object p only points at the object with dynamic storage duration. The p object itself has an automatic storage duration. To delete the object on the heap, we need to use the delete operator.

22.3 Automatic and Dynamic Storage Durations

Write a program that defines a variable of type int called x, automatic storage duration, and a variable of type int* which points to an object with dynamic storage duration. Both variables are in the same scope:
#include <iostream>
int main()
{
    int x = 123; // automatic storage duration
    std::cout << "The value with an automatic storage duration is: " << x << ' ';
    int* p = new int{ x }; // allocate memory and copy the value from x to it
    std::cout << "The value with a dynamic storage duration is: " << *p << ' ';
    delete p;
} // end of scope here
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.185.147