Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to allocate, fill, print, and deallocate a 2D array in C++

1 Answer

0 votes
#include <iostream>

// Function to allocate a 2D array
int** allocateArray(int rows, int cols) {
    int** array = new(std::nothrow) int * [rows];
    if (array == nullptr) {
        std::cout << "Memory allocation failed for rows." << "\n";
        return nullptr;
    }

    for (int i = 0; i < rows; i++) {
        array[i] = new(std::nothrow) int[cols];
        if (array[i] == nullptr) {
            std::cout << "Memory allocation failed for row " << i << "." << "\n";
            for (int j = 0; j < i; j++) {
                delete[] array[j];
            }
            delete[] array;
            return nullptr;
        }
    }

    return array;
}

// Function to fill the array with values
void fillArray(int** array, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            array[i][j] = (i + 1) * (j + 1); 
        }
    }
}

// Function to print the array
void printArray(int** array, int rows, int cols) {
    std::cout << "2D Array Values:" << "\n";
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << array[i][j] << " ";
        }
        std::cout << "\n";
    }
}

// Function to deallocate the array
void deallocateArray(int** array, int rows) {
    for (int i = 0; i < rows; i++) {
        delete[] array[i];
    }
    delete[] array;
}

int main() {
    int rows = 3, cols = 4;

    int** array = allocateArray(rows, cols);
    if (array == nullptr) {
        return 1;
    }

    fillArray(array, rows, cols);
    printArray(array, rows, cols);
    deallocateArray(array, rows);
}




/*
run:
   
2D Array Values:
1 2 3 4 
2 4 6 8 
3 6 9 12 
 
*/

 



answered Aug 8, 2025 by avibootz

Related questions

...