Skip to content

Array implementation by pointers

#include <iostream>

using namespace std;

void printElements(int **haha, int size1, int size2);

int main() {
    // Initialize the array sizes
    const int size1 = 4, size2 = 3;

    // Define a pointer to a pointer (for a 2D array)
    int **ptr;

    // Initialize the 2D array
    ptr = new int*[size1];
    for (int i = 0; i < size1; ++i) {
        ptr[i] = new int[size2];
    }

    // Assign values to the 2D array and print them
    for (int i = 0; i < size1; ++i) {
        for (int j = 0; j < size2; ++j) {
            ptr[i][j] = i + j;  // Example assignment
        }
    }

    // Print the elements using the function
    printElements(ptr, size1, size2);

    // Deallocate memory
    for (int i = 0; i < size1; ++i) {
        delete[] ptr[i];
    }
    delete[] ptr;

    return 0;
}

void printElements(int **haha, int size1, int size2) {
    cout << "Elements in the array:" << endl;
    for (int i = 0; i < size1; ++i) {
        for (int j = 0; j < size2; ++j) {
            cout << haha[i][j] << " ";
        }
        cout << endl;
    }
}

Oh hi there 👋 It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.