Page 19 - Data Structures Interactive Book
P. 19

1.4.1  Dynamic Allocation


                       Dynamic allocation refers to requesting memory at runtime rather than at compile

               time. In C++, this is achieved using the new operator, which allocates memory on the heap,

               and the delete operator, which releases it. Dynamic allocation is particularly useful when the

               size of data structures cannot be determined in advance. For example, when creating a linked

               list, each node is allocated dynamically as the program runs. Proper use of delete ensures that
               memory is freed once it is no longer needed, preventing memory leaks.

                 Example:




















                         This program demonstrates how to allocate memory dynamically for an integer, assign a

              value, and then release the memory.


               1.4.2  Pointers


                       Pointers are variables that store memory addresses rather than actual values. They
               are fundamental in C++ because they enable direct manipulation of memory and efficient

               handling  of  data  structures.  A  pointer  can  be  used  to  reference  variables,  arrays,  or

               dynamically  allocated  memory.  By  dereferencing  a  pointer  (using  the  *  operator),

               programmers can access or modify the value stored at the memory location. Pointers are
               essential for implementing linked lists, trees, and other dynamic structures.











                                                             19
   14   15   16   17   18   19   20   21   22   23   24