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

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

    // Allocate memory for a 2D array using a pointer to an array
    int (*arr)[cols] = (int (*)[cols])malloc(rows * cols * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initialize the array
    int value = 1;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            arr[i][j] = value++;
        }
    }

    // Access elements
    printf("Accessing dynamically allocated 2D array using pointer to an array:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }

    // Free memory
    free(arr);

    return 0;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter