#include <stdio.h>
#include <stdlib.h>
int** allocateMatrix(int rows, int cols) {
int** matrix = (int**)malloc(rows * sizeof(int*)); // Allocate rows
if (matrix == NULL) {
printf("Memory allocation failed for rows!\n");
return NULL;
}
for (int i = 0; i < rows; i++) {
matrix[i] = (int*)malloc(cols * sizeof(int)); // Allocate columns
if (matrix[i] == NULL) {
printf("Memory allocation failed for row %d!\n", i);
return NULL;
}
}
return matrix; // Return pointer to the matrix
}
void freeMatrix(int** matrix, int rows) {
for (int i = 0; i < rows; i++) {
free(matrix[i]); // Free each row
}
free(matrix); // Free the array of pointers
}
void initializeMatrix(int** matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = i * cols + j;
}
}
}
void printMatrix(int** matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%2d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int rows = 3, cols = 4;
// Allocate memory for the matrix
int** matrix = allocateMatrix(rows, cols);
if (matrix == NULL) {
return 1; // Exit if memory allocation fails
}
// Initialize and print the matrix
initializeMatrix(matrix, rows, cols);
printMatrix(matrix, rows, cols);
// Free allocated memory
freeMatrix(matrix, rows);
return 0;
}
/*
run:
0 1 2 3
4 5 6 7
8 9 10 11
*/