template style matrix implementation in c

Posted by monkeyking on Stack Overflow See other posts from Stack Overflow or by monkeyking
Published on 2010-04-05T09:49:34Z Indexed on 2010/04/05 9:53 UTC
Read the original article Hit count: 293

Filed under:
|
|
|

From time to time I use the following code for generating a matrix style datastructure

typedef double myType;

typedef struct matrix_t{                                                             |Compilation started at Mon Apr  5 02:24:15
  myType **matrix;                                                                   |
  size_t x;                                                                          |gcc structreaderGeneral.c -std=gnu99 -lz
  size_t y;                                                                          |
}matrix;                                                                             |Compilation finished at Mon Apr  5 02:24:15
                                                                                     |
                                                                                     |
matrix alloc_matrix(size_t x, size_t y){                                             |
  if(0)                                                                              |
    fprintf(stderr,"\t-> Alloc matrix with dim (%lu,%lu) byteprline=%lu bytetotal:%l\|
u\n",x,y,y*sizeof(myType),x*y*sizeof(myType));                                       |
                                                                                     |
  myType **m = (myType **)malloc(x*sizeof(myType **));                               |
  for(size_t i=0;i<x;i++)                                                            |
    m[i] =(myType *) malloc(y*sizeof(myType *));                                     |
                                                                                     |
  matrix ret;                                                                        |
  ret.x=x;                                                                           |
  ret.y=y;                                                                           |
  ret.matrix=m;                                                                      |
  return ret;                                                                        |
} 

And then I would change my typedef accordingly if I needed a different kind of type for the entries in my matrix.

Now I need 2 matrices with different types, an easy solution would be to copy/paste the code, but is there some way to do a template styled implementation.

Thanks

© Stack Overflow or respective owner

Related posts about c

    Related posts about c++