9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia08/ex10.c (959B)
   1 #include <stdio.h>
   2 #include <stdlib.h>
   3 
   4 double **identity_matrix(size_t dim);
   5 
   6 int main (void)
   7 {
   8     double **m;
   9     size_t len = 3;
  10     m = identity_matrix(len);
  11 
  12     for(size_t i = 0; i < len; i++) {
  13         for(size_t j = 0; j < len; j++)
  14             printf("%.0f ", m[i][j]);
  15 
  16         putchar('\n');
  17     }
  18 
  19     return 0;
  20 }
  21 
  22 double **identity_matrix(size_t dim)
  23 {
  24     double **m;
  25     
  26     /* Allocates memory for a squared matrix of dimension dim */
  27     if(!(m = (double **)malloc(sizeof(double) * (dim * dim)))) return NULL;
  28 
  29     /* Gets memory for every element of the matrix, if an error occurs, frees every previous allocated element and returns null, if no errors are enconuntered and both indexes are equal stores a 1 otherwise leaves it at zero */
  30     for(size_t i = 0; i < dim; i++) {
  31         if(!(m[i] = (double *)calloc(sizeof(double), dim))) {
  32             for(size_t k = i; k--;) free(m[k]);
  33             return NULL;
  34         }
  35         for(size_t j = 0; j < dim; j++) {
  36             if(i == j) m[i][j] = 1;
  37             else m[i][j] = 0;
  38         }
  39     }
  40 
  41     return m;
  42 }