Associate Professor of Computer Science
C++ Primer For Java Programmers
Pointers Table of Contents Arrays
To create or allocate a dynamic variable, you use the
int x = 5; // static variable.
int *p; // static variable.
p = new int; // allocate a dynamic int variable.
which allocates two static variables
After a dynamic variable is created, it can be used just like any other variable, the only difference is that it must be indirectly accessed using the pointer to which it was assigned. We can initialize the newly created dynamic variable using the statement
*p = 40;
Once the dyanmic variable has been initialized, it can then be used. The following statement uses the value in the dynamic variable pointed to by
x = x + *p
This statement modifies the value of
Unlike Java and Python, C++ does not provide garbage collection and thus does not automatically deallocate dynamic variables when you are finished with them. You are responsible for deallocating any dynamic variable you create when you no longer need it.
To delete a previously allocated dynamic variable, you use the
p = NULL;
When a dynamic variable is destroyed, the corresponding pointer variable is not modified. It is good practice, however, to set the pointer to NULL to prevent the accidental resuse later in your program.
Standard C Memory Allocation
To allocate dynamic memory using the standard C approach, we call
int *pInt = (int *) malloc( sizeof( int ) );
When the dynamic variable is allocated,
To deallocate dynamic memory previoulsy allocated with
free( pInt );
pInt = NULL;