c - 如何为 GSL 矩阵重新分配内存(例如添加一行)?

标签 c memory-management gsl

如果我有一个已经分配内存的 GSL 矩阵,是否有一种简单的方法可以重新分配该内存,例如,添加另一行?

我能想到的两种方法是:

size_t n = 2;
gsl_matrix invV = gsl_matrix_alloc(n, n);
// do something with matrix
...
// try and add another row (of length n) by reallocating data in the structure
invV->data = realloc(invV->data, sizeof(double)*(n*n + n));
invV->size1++;

或(使用矩阵 View ):

size_t n = 2;
double *invV = malloc(sizeof(double)*n*n)
gsl_matrix_view invVview = gsl_matrix_view_array(invV, n, n);
// do something with &invVview.matrix
...
// try adding another row or length n
invV = realloc(invV, invV->data, sizeof(double)*(n*n + n));
invView = gsl_matrix_view_array(invV, n+1, n);

我不知道第一种方法是否存在问题,因为没有更改 gsl_matrix 中的 tdablockstructure .有谁知道这是否会成为问题?

第二种方法工作正常,但必须在 double 数组和矩阵 View 之间来回切换很痛苦。

欢迎提出其他建议。

更新:

我有一个简单的测试代码,它使用了我的第一个选项的一个版本(例如,称为 testgsl.c):

#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>

gsl_matrix *matrix_add_row( gsl_matrix *m);

gsl_matrix *matrix_add_row( gsl_matrix *m ){
  if ( !m ){
    fprintf(stderr, "gsl_matrix must have already been initialised before adding new rows" );
    return NULL;
  }  

  size_t n = m->tda; /* current number of columns in matrix */

  /* reallocate the memory of the block */
  m->block->data = (double *)realloc(m->block->data, sizeof(double)*(m->block->size + n));
  if( !m->block->data ){
    fprintf(stderr, "Could not reallocate memory for gsl_matrix!");
    exit(1);
  }
  m->block->size += n;      /* update block size (number of elements) */
  m->size1++;               /* update number of rows */
  m->data = m->block->data; /* point data to block->data */
  return m;
}

int main( int argc, char **argv){
  size_t nrows = 4;
  size_t ncols = 1000;
  gsl_matrix *invV = gsl_matrix_alloc(nrows, ncols);

  //gsl_matrix *testmatrix = gsl_matrix_alloc(1000, 4000);

  /* set to zeros */
  gsl_matrix_set_zero( invV );

  /* try adding a row */
  invV = matrix_add_row( invV );

  fprintf(stderr, "nrows = %zu, ncols = %zu\n", invV->size1, invV->size2);

  /* set some values */
  gsl_matrix_set_zero( invV );
  gsl_matrix_set( invV, 4, 0, 2.3 );
  gsl_matrix_set( invV, 4, 1, 1.2 );

  gsl_matrix_free( invV );
  //gsl_matrix_free( testmatrix );

  return 0;
}

这似乎工作正常(尽管我认为可能会出现一些潜在的内存分配问题)。

最佳答案

Brian Goughgsl_matrix 代码的作者之一,似乎 suggest这是我的第二个选择——重新分配数组,并在必要时只使用 vector/矩阵 View 。

关于c - 如何为 GSL 矩阵重新分配内存(例如添加一行)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36774521/

相关文章:

c - 本地指针, `static` 指针和 `malloc` 指针

node.js : async. 由于大量元素而导致异步处理速度太慢

c++ - 如何确定 C++ 中对象的大小?

c - $n( Bison 的规则)返回上一个标记读取的值

c - unsigned char 和 char 异或运算

c++ - Valgrind 在不应该的时候报告竞争条件

c - valgrind 错误 : invalid read

haskell - hmatrix 的 ghc 问题

c - GSL 线性代数示例失败

c++ - Rcpp 找不到 gsl 库