泛型矩阵:如何在函数参数中传递类型

时间:2013-05-23 07:45:27

标签: c generics matrix

我创建了一个像这样的通用矩阵结构:

typedef struct mat_t {
  /**
   * \brief matrix structure
   */
  unsigned int c, l;
  void **matrice;
}* mat;

我的问题是学习如何为矩阵分配内存,因为它可以包含复数,浮点数或其他... 因此,我想知道如何将类型传递给我的函数参数以获得分配内存。

mat allocate_mat(unsigned int l, unsigned int c, **<type>** )

也许,我应该为这个函数使用一个定义宏吗?

3 个答案:

答案 0 :(得分:1)

  

也许,我应该为这个函数使用一个定义宏吗?

是的,你可以定义一个宏来在最后一个参数中取一个类型,并调用在最后一个参数中取一个大小的实函数。

#define allocate_mat(MAT_L, MAT_C, MAT_TYPE) allocate_mat_sz(MAT_L, MAT_C, sizeof(MAT_TYPE))
mat allocate_mat_sz (unsigned l, unsigned c, size_t size);

答案 1 :(得分:1)

问题1:奇怪的变量名称。 lc应该是什么意思? “行”,“数”? C中没有任何内容阻止您将完整单词用作变量名...

问题2:你最有可能使用一个假的二维数组,指针到指针表示法,这会导致堆碎片惨败。它不仅速度慢而且导致堆碎片,它也不能用于基本的C函数,如memset(),memcpy()。相反,在相邻的内存中分配一个真正的2D数组。

问题3:为什么在struct typedef的末尾有* mat?这没有任何意义。

以下是使用通用C编程的动态矩阵的基本实现:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef struct mat_t
{
  void** data;
  size_t row_n;
  size_t col_n;
  size_t obj_size;
} matrix_t;


bool matrix_init (matrix_t* mat, 
                  size_t    row_n, 
                  size_t    col_n,
                  size_t    obj_size)
{
  mat->row_n = row_n;
  mat->col_n = col_n;
  mat->obj_size = obj_size;

  mat->data = calloc(row_n * col_n, obj_size);

  return mat->data != NULL;
}


void matrix_free (matrix_t* mat)
{
  free(mat);
}


void matrix_set (matrix_t* mat,
                 size_t    x,
                 size_t    y,
                 void*     val)
{
  size_t data_offset = y * mat->row_n * mat->obj_size + 
                       x * mat->obj_size;

  memcpy (mat->data + data_offset,
          val,
          mat->obj_size);
}


void* matrix_get (const matrix_t* mat,
                  size_t x,
                  size_t y)
{
  size_t data_offset = y * mat->row_n * mat->obj_size + 
                       x * mat->obj_size;

  return mat->data + data_offset;
}


int main()
{
  matrix_t mat;
  const int ROWS=3;
  const int COLS=2;

  // allocate memory
  matrix_init(&mat, ROWS, COLS, sizeof(int));


  // fill memory with data 1,2,3...
  int count =0;
  for(int row=0; row<ROWS; row++)
  {
    for(int col=0; col<COLS; col++)
    {
      count++;
      matrix_set (&mat, row, col, &count);
    }
  }

  // print the matrix
  for(int row=0; row<ROWS; row++)
  {
    printf("[ ");
    for(int col=0; col<COLS; col++)
    {
      printf("%d ", *(int*)matrix_get(&mat, row, col));
    }
    printf("]\n");
  }

  matrix_free(&mat);
  return 0;
}

答案 2 :(得分:0)

您可以传递矩阵元素的大小:

mat allocate_mat(unsigned int l, unsigned int c, unsigned int size_of_matrix_element )
相关问题