Dynamic Memory Allocation
Task 1
Code
- #include<iostream>
- using namespace std;
- int main(){
- int *p;
- int num1 = 5;
- int num2 = 8;
- p = &num1; //store the address of num1 into p
- *p = 10;
- cout << endl;
- cout<< "Line 1: &num 1 = " << &num1 << ", p = " << p << endl;
- cout<< "Line 2: &num 1 = " << &num1 << ", *p = " << *p << endl << endl;
- p = &num2; //store the address of num2 into p
- cout<< "Line 3: &num 2 = " << &num2 << ", p = " << p << endl; //line1 & line3 print different value
- cout<< "Line 4: &num 2 = " << &num2 << ", *p = " << *p << endl << endl;
- *p = 2 * (*p);
- cout << "Line 5: num2 = " << num2 << " , *p = " << *p << endl << endl;
- delete p;
- return 0;
- }
Output
Line 1: &num 1 = 0x61ff08, p = 0x61ff08
Line 2: &num 1 = 0x61ff08, *p = 10
Line 3: &num 2 = 0x61ff04, p = 0x61ff04
Line 4: &num 2 = 0x61ff04, *p = 8
Line 5: num2 = 16 , *p = 16
Task 2
Code
- #include<iostream>
- using namespace std;
- int main(){
- int *p;
- int *q;
- p = new int;
- *p = 120;
- cout << "Line 1: p = " << p << ", *p=" << *p << endl << endl;
- q = p;
- cout << "Line 2: q = " << q << ", *q=" << *q << endl << endl;
- *q = 500;
- cout << "Line 3: p = " << p << ", *p=" << *p << endl;
- cout << "Line 4: q = " << q << ", *q=" << *q << endl << endl;
- p = new int;
- *p =180;
- cout << "Line 5: p = " << p << ", *p=" << *p << endl;
- cout << "Line 6: q = " << q << ", *q=" << *q << endl<< endl;
- delete q;
- // cout << *q; //print garbage value
- // cout << q; //print same address
- q = NULL;
- q = new int;
- *q = 620;
- cout << "Line 7: p = " << p << ", *p=" << *p << endl;
- cout << "Line 8: q = " << q << ", *q=" << *q << endl<< endl;
- delete p;
- delete q;
- return 0;
- }
Output
Line 1: p = 0x1e6d88, *p=120
Line 2: q = 0x1e6d88, *q=120
Line 3: p = 0x1e6d88, *p=500
Line 4: q = 0x1e6d88, *q=500
Line 5: p = 0x1e6d98, *p=180
Line 6: q = 0x1e6d88, *q=500
Line 7: p = 0x1e6d98, *p=180
Line 8: q = 0x1e6d88, *q=620
0 Comments