c - Allocating space for upper triangular matrices in algebraic notation -


i'm working on project (written in c) involving matrix factorization , need help. objective allocate memory upper triangular matrix , want access via algebraic row , column notation (i.e. i,j in {1,2,...,n} instead of i,j in {0,1,...,n-1}). example, in 5x5 matrix should able access [3][4] element if input matrix[3][4].

my code non-algebraic index upper triangular matrix looks this:

double** malloc_sup_matrix (int n) {     double**    l;     int         i;      l = (double**)malloc((n)*sizeof(double*));      if(l == null)         printerror("allocating space matrix (rows).");              for(i = 0;  < n;  i++)     {         l[i] = (double*)malloc((n-i)*sizeof(double));         if(l[i] == null)             printerror("allocating space matrix (cols).");         l[i]-=i;     }     return l; } 

my code algebraic index 1 (i'm not checking if allocated space null yet, i'll when stop messing around this):

    int**   m;     int     i, n;      n = 10;      m = (int**)malloc((n+1)*sizeof(int*));     for(i = 0; < n; i++)     {         m[i] = (int*)calloc((n+1)-(i),sizeof(int));         m[i] -= i;     }      m--;     for(i = 0; < n; i++)     {         m[i]--;     } 

it works way want it, but have issues when freeing space i've used. way i'm doing it:

    for(i = 1; <= n; i++)     {         m[i]++;     }          for(i = 0; < n; i++)     {         m[i] += (i);         free(m[i]);     }     m++;     free(m); 

do guys have suggestions? thank in advance ^^.

there's problem on line:

m--; for(i = 0; < n; i++) {     m[i]--; } 

you're decrementing m, go ahead , index 0 ... guess may end messing heap structures.

i managed have code valgrind error-free this:

#include <stdio.h> #include <string.h> #include <stdlib.h>   int main(int argc, char *argv[]) {     int**   m;     int     i, j, n;      n = 10;      m = (int**)malloc((n+1)*sizeof(int*));     for(i = 0; < n; i++)     {         m[i] = (int*)calloc((n+1)-(i), sizeof(int));         m[i] -= i;     }      for(i = 0; < n; i++)     {         m[i]--;     }      m--;      /* access m[1][1] ... m[n][n], m[i][j] (with <= j) */      /*     (i = 1; <= n; i++) {         (j = i; j <= n; j++) {             m[i][j] = i+j;         }     }     */      m++;      for(i = 0; < n; i++)     {         m[i]++;     }      for(i = 0; < n; i++)     {         m[i] += (i);         free(m[i]);     }      free(m);      return 0; } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -