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!
new
there must be a delete
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;
Given int a[4] = {1,2,3,4}
a
↔ &a[0]
*a
↔ a[0]
*(a+1)
↔ a[1]
We can dynamically allocate memory for the array
int size = 7;
int* arr = new int[size];
int** arr2p = new int* [4];
for(int i = 0; i< 4; i++){ arr2p[i] = new int}
for(int i = 0; i<4; i++){*arr2p[i] = i+1;}
for(int i = 0; i<4; i++){
delete arr2p[i];
arr2p[i] = NULL; //good practice
}
delete[] arr2p;
arr2p = NULL;
#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;
}
#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;
}