Access 2d array with pointer C

#include <stdio.h>

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

    // Allocate memory for a 2D array
    int matrix = (int)malloc(rows  sizeof(int));
    for (int i = 0; i < rows; i++) {
        matrix[i] = (int)malloc(cols  sizeof(int));
    }

    // Initialize the 2D array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = i * cols + j + 1;
        }
    }

    // Access elements using pointer arithmetic
    int ptr = (int)matrix;
    for (int i = 0; i < rows * cols; i++) {
        printf("%d ", *(ptr + i));
        if ((i + 1) % cols == 0) {
            printf("\n");
        }
    }

    // Deallocate memory
    for (int i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);

    return 0;
}