Pointers

Pointers

Pointers are objects of pointer type. Pointers point at some memory location. To declare a pointer of certain type we append a * to the type name. Example:

#include <iostream>
int main(){
	int* p; // pointer to an integer value
	char* p2; // pointer to a char value
}

This declares a pointer of type int*. To initialize a pointer to point to some variable we use the address-of & operator:

#include <iostream>
int main(){
	int x = 123;
	int* p = &x; // points to x
    
	char c = 'A';
	char* p2 = &c; // points to c
}

To print out or modify the value pointed to by pointer we prepend the pointer variable name with the * symbol:

#include <iostream>
int main(){
	int x = 123;
	int* p = &x;
	std::cout << *p;
	*p = 456;
	std::cout << *p;
}

Pointers can be initialized to point to an array. In that case the pointer points at the first element of an array. arr[0]

#include <iostream>
int main(){
	int arr[5] = { 1, 2, 3, 4, 5 };
	int* p = arr;
	std::cout << *p; // prints out the first element
}

new - delete

Memory can be dynamically allocated using the new operator and freed using the delete operator:

#include <iostream>
int main()
{
	int* p = new int(123); // allocate space for one integer and assign the value of 123 to it
	delete p;
}

To dynamically allocate space for an array use the new type [] approach and free the memory using the delete [] operator:

#include <iostream>
int main()
{
	int* p = new int[5]; // allocate space for an array of 5 integers
	delete[] p;
}

Prefer smart pointers instead

That being said the prefered way of allocating memory and working with pointers nowadays is through the use of smart pointers such as std::unique_ptr and std::shared_ptr.