Dynamic Memoray alocation For 2D

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

int main() {
    int rows, cols, i, j;

    // Step 1: Input the number of rows and columns
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    printf("Enter the number of columns: ");
    scanf("%d", &cols);

    // Step 2: Dynamically allocate memory for the 2D array
    int matrix = (int )malloc(rows  sizeof(int ));
    for (i = 0; i < rows; i++) {
        matrix[i] = (int )malloc(cols  sizeof(int));
    }

    // Step 3: Input elements into the 2D array
    printf("Enter the elements of the matrix:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    // Step 4: Display the 2D array
    printf("The entered matrix is:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }

    // Step 5: Free the dynamically allocated memory
    for (i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);

    return 0;
}