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,971 questions

51,913 answers

573 users

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

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

// Function to allocate a 2D array
int** allocateArray(int rows, int cols) {
    int** array = (int**)malloc(rows * sizeof(int*));
    if (array == NULL) {
        printf("Memory allocation failed for rows.\n");
        return NULL;
    }

    for (int i = 0; i < rows; i++) {
        array[i] = (int*)malloc(cols * sizeof(int));
        if (array[i] == NULL) {
            printf("Memory allocation failed for row %d.\n", i);
            for (int j = 0; j < i; j++) {
                free(array[j]);
            }
            free(array);
            return NULL;
        }
    }

    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) {
    printf("2D Array Values:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", array[i][j]);
        }
        printf("\n");
    }
}

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

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

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

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

    return 0;
}


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

*/



 



answered Aug 8, 2025 by avibootz

Related questions

...