Integers

int x;
int* p; //p is a pointer
x=7;
p = NULL;
p = &x; //p now stores the address of x
*p = 5// deference p, so we change the value of x to 5
p = new int; //change address stored in p to a newly allocated memory space
*p = 3; //change value at address 0x560 instaed of x's address

//before exiting, we should return dynamically allocated memory to operating system
delete p;
p = nullptr; //good practice!

Double Pointers

int** p2p; //stores the address of a pointer 
int* p;
int* q;

p2p = &p;
q = *p2p; // q will store the vaue of p
*q = 8;

Arrays

Dynamically allocating an array of pointers to integers

for(int i = 0; i<4; i++){
	delete arr2p[i];
	arr2p[i] = NULL; //good practice
}

delete[] arr2p;
arr2p = NULL;

Untitled

Dynamic allocation of an array of objects

#include <iostream>
#include <string>
using namespace std;
class Student{
    public: 
        string name;
        int ID;
        Student(){ID = 0; name = "";}
        ~Student(){
            cout << "Destructor" << endl;
        }
};

int main(){
    Student* arr = new Student[3]; //default constructor called 3 times

    delete[] arr; //destructor called 3 times

    return 0;
}

Dynamic allocation of an array of pointers to objects

Untitled

#include <iostream>
#include <string>
using namespace std;
class Student{
    public: 
        string name;
        int ID;
        Student(){ID = 0; name = "";}
        ~Student(){
            cout << "Destructor" << endl;
        }
};

int main(){
    Student** arr2p = new Student* [3];

    for(int i = 0; i<3; i++){
        arr2p[i] = new Student;
    }

    for(int i = 0; i< 3; i++){
        arr2p[i] -> ID = i+1;
    }

    //and now free the memory
    for(int i = 0; i<3; i++){
        delete arr2p[i];
    }

    delete[] arr2p;
    arr2p = NULL;
}