9511_workbook

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