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

void matrix_allocation(int ***matrix, int N){
    int i;
    /* dynamic allocation for the matrix */
    /*allocation of the rows*/
    *matrix = (int**)malloc(N * sizeof(int*));  
    if((*matrix) == NULL){
    	printf("\n Error in memory allocation for the matrix \n");
    }
    /*allocation of the coloumns*/
    for(i=0; i<N; i++){   
    	(*matrix)[i]=(int*) malloc(N * sizeof(int));
    	if ((*matrix)[i] == NULL){
        	printf("Cannot allocate enough memory\n");
        }
    }
}

void generate_matrix(int **matrix, int N){
    int i, j;
    for (i=0; i<N; i++){
        for (j=0; j<N; j++){
                    if(i==j){                   //the diagonal must be 0
                        matrix[i][j] = 0;
                        printf("%i\t", matrix[i][j]);
                    } else {
            			matrix[i][j] = rand()%10;
                        printf("%i\t", matrix[i][j]);
           
                    }
        }
                printf("\n");
    }
    printf("\nMatrix generated successfully!\n");
}

void free_matrix(int **matrix, int N) {
	int i;
	for(i = 0; i < N; i++) free(matrix[i]);
	free(matrix);
}
int main(void) {
	int **matrix;
	matrix_allocation(&matrix, 5);
	generate_matrix(matrix, 5);
	free_matrix(matrix, 5);
	return 0;
}
