
Dynamic Memory Allocation, Shallow & Deep Copy, Array
Task 1:
Code
#include <iostream>
using namespace std;
int main()
{
    int *firstArray;
    int *secondArray;
    firstArray = new int[10];
    for (int i = 0; i < 10; i++)
    {
        firstArray[i] = i + 1;
    }
    cout << "Shallow Copy" << endl;
    secondArray = firstArray; //shallow copy
    for (int i = 0; i < 10; i++)
    {
        cout << secondArray[i] << " ";
    }
    delete [] firstArray; //second array also become invalid
    cout << endl << "Deep Copy" << endl;
    firstArray = new int[10];
    secondArray = new int[10];
    for (int i = 0; i < 10; i++)
    {
        firstArray[i] = i+1;
    }
    for (int j = 0; j < 10; j++) //deep copy
    {
        secondArray[j] = firstArray[j];
    }
    delete[] firstArray; //second array remains valid
    for (int i = 0; i < 10; i++)
    {
        cout << secondArray[i] << " ";
    }
    return 0;
}
Output
Shallow Copy
1 2 3 4 5 6 7 8 9 10 
Deep Copy
1 2 3 4 5 6 7 8 9 10
Task 02:
Code
#include<iostream>
using namespace std;
int main(){
    int value1 = 25;
    int* ptr1;
    int** pptr1;
    ptr1 = &value1;
    pptr1 = &ptr1;
    cout << value1 << " " << *ptr1 << " " << **pptr1 << endl << endl;
    int value2 = 15;
    int* ptr2;
    int** pptr2;
    ptr2 = &value2;
    pptr2 = &ptr2;
    cout << value2 << " " << *ptr2 << " " << **pptr2 << endl << endl;
    ptr2 = ptr1; //updating ptr2 with ptr1
    cout << value2 << " " << *ptr2 << " " << **pptr2 << endl << endl;
    return 0;
}
Output
25 25 25
15 15 15
15 25 25
Task 03:
Code
#include<iostream>
using namespace std;
int main(){
    int** myArray = new int* [5];
    for (int i = 0; i < 5; i++)
    {
        myArray[i] = new int[5];
    }
    for (int j = 0; j < 10; j++)
    {
        myArray[j] = new int[10];
    }
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            myArray[i][j] = i+j+1;
        }
    }
    cout << endl;
    for (int i = 0; i < 5; i++)  //using array index
    {
        for (int j = 0; j < 10; j++)
        {
            cout << myArray[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl << endl;
    for (int i = 0; i < 5; i++) //using pointers
    {
        for (int j = 0; j < 10; j++)
        {
            cout << *(*(myArray+i)+j) << " ";
        }
        cout << endl;
    }
    cout << endl << endl;
    return 0;
}
Output
1 2 3 4 5 6 7 8 9 10 
2 3 4 5 6 7 8 9 10 11 
3 4 5 6 7 8 9 10 11 12 
4 5 6 7 8 9 10 11 12 13 
5 6 7 8 9 10 11 12 13 14 
1 2 3 4 5 6 7 8 9 10
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12 13
5 6 7 8 9 10 11 12 13 14
 
0 Comments