init
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
int **allocate_matrix(int rows, int cols)
|
||||
{
|
||||
int **matrix = malloc(rows * sizeof(int *));
|
||||
if (!matrix)
|
||||
return NULL;
|
||||
for (int i = 0; i < rows; i++)
|
||||
{
|
||||
matrix[i] = malloc(cols * sizeof(int));
|
||||
if (!matrix[i])
|
||||
{
|
||||
for (int j = 0; j < i; j++)
|
||||
free(matrix[j]);
|
||||
free(matrix);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
return matrix;
|
||||
}
|
||||
|
||||
void free_matrix(int **matrix, int rows)
|
||||
{
|
||||
if (!matrix)
|
||||
return;
|
||||
free(matrix);
|
||||
return;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int rows = 5;
|
||||
int cols = 5;
|
||||
int **matrix = allocate_matrix(rows, cols);
|
||||
if (!matrix)
|
||||
{
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
for (int i = 0; i < rows; i++)
|
||||
{
|
||||
for (int j = 0; j < cols; j++)
|
||||
{
|
||||
matrix[i][j] = i * cols + j;
|
||||
}
|
||||
}
|
||||
|
||||
free_matrix(matrix, rows);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
Reference in New Issue
Block a user