Online C Compiler - Programiz
Sun Jan 26 2025 01:00:48 GMT+0000 (Coordinated Universal Time)
Saved by
@Narendra
#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;
}
content_copyCOPY
https://www.programiz.com/c-programming/online-compiler/
Comments