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

1 answer 81 views
2 answers 233 views
1 answer 234 views
1 answer 220 views
1 answer 78 views
...