fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void matrix_allocation(int ***matrix, int N){
  5. int i;
  6. /* dynamic allocation for the matrix */
  7. /*allocation of the rows*/
  8. *matrix = (int**)malloc(N * sizeof(int*));
  9. if((*matrix) == NULL){
  10. printf("\n Error in memory allocation for the matrix \n");
  11. }
  12. /*allocation of the coloumns*/
  13. for(i=0; i<N; i++){
  14. (*matrix)[i]=(int*) malloc(N * sizeof(int));
  15. if ((*matrix)[i] == NULL){
  16. printf("Cannot allocate enough memory\n");
  17. }
  18. }
  19. }
  20.  
  21. void generate_matrix(int **matrix, int N){
  22. int i, j;
  23. for (i=0; i<N; i++){
  24. for (j=0; j<N; j++){
  25. if(i==j){ //the diagonal must be 0
  26. matrix[i][j] = 0;
  27. printf("%i\t", matrix[i][j]);
  28. } else {
  29. matrix[i][j] = rand()%10;
  30. printf("%i\t", matrix[i][j]);
  31.  
  32. }
  33. }
  34. printf("\n");
  35. }
  36. printf("\nMatrix generated successfully!\n");
  37. }
  38.  
  39. void free_matrix(int **matrix, int N) {
  40. int i;
  41. for(i = 0; i < N; i++) free(matrix[i]);
  42. free(matrix);
  43. }
  44. int main(void) {
  45. int **matrix;
  46. matrix_allocation(&matrix, 5);
  47. generate_matrix(matrix, 5);
  48. free_matrix(matrix, 5);
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
0	3	6	7	5	
3	0	5	6	2	
9	1	0	2	7	
0	9	3	0	6	
0	6	2	6	0	

Matrix generated successfully!