Variables

Pointers in C++

To store a reference is to store an address in the memory of a variable. A pointer is a variable itself and has a value whereas a reference only has a variable that it is referencing.


Syntax
dataType *pointerName = &Variable; //Pointer 
dataType &referenceName = Variable; //Reference 
 
//Memory allocation of the pointer of a specified size, usually of a certain data type
dataType *pointerName = malloc(desired_allocation_size);  
 
delete pointerName; //Free the memory used by the pointer.

Notes

To access the memory address of any variable (stack included), use the & symbol. This is to reference.

Memory is assigned to pointer variables at runtime and not at compile time. Memory is not directly manipulated, like with stack variables, rather the memory address stores variable's value.

Pointer variables allow the programmer to get the memory address as well as the value. By default, if you were to access the pointer variable as you would a stack variable, you would receive the memory address. This is known as referencing.

To access the value stored at the memory address, add an asterisk. This is known as dereferencing.

C++ does not have garbage collection, so after allocating memory to the variable during runtime, you need to free that memory.


Example
using namespace std;

int x = 5; 
int *pointer = &x; //referencing the memory address of x, and storing it in a pointer variable
 
//creating a pointer variable, and allocating memory for it during runtime
int *newPointer = malloc(sizeof(int)); 
cout << newPointer; //will print the address in the pointer variable
*newPointer = 5; //placing a value at the memory address
 
cout << *newPointer; //dereferencing the pointer to print the value
 
delete newPointer; //free the memory once done the operation on the variable

See Also
Documentation

Pointers - C++ Reference

Add to Slack

< Array   |   Structures >

© 2019 SyntaxDB. All Rights Reserved.