Dynamic 2D Array
C
Medium
4 views
Problem Description
Take rows and columns input from the user. Allocate the second array using malloc. Fill in the values, print them, then free the property. There should be no memory leaks.
Official Solution
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows, cols;
int **arr;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);
/* Allocate array of pointers (for rows) */
arr = (int **)malloc(rows * sizeof(int *));
if (arr == NULL) {
printf("Memory allocation failed!n");
return 1;
}
/* Allocate each row */
for (int i = 0; i < rows; i++) {
arr[i] = (int *)malloc(cols * sizeof(int));
if (arr[i] == NULL) {
printf("Memory allocation failed!n");
/* Free previously allocated rows */
for (int j = 0; j < i; j++)
free(arr[j]);
free(arr);
return 1;
}
}
/* Fill values */
printf("Enter the elements:n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &arr[i][j]);
}
}
/* Print the array */
printf("n2D 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 */
for (int i = 0; i < rows; i++)
free(arr[i]);
free(arr);
printf("nMemory freed successfully.n");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!