【问题标题】:Passing GSL arrays to other functions将 GSL 数组传递给其他函数
【发布时间】:2014-11-02 03:21:18
【问题描述】:

我是使用 GSL 的新手,我想知道如何将 GSL 数组从一个函数返回到另一个函数。它不像一个普通的数组......我一直试图弄清楚这一点,但我没有强大的 C 背景,这让我发疯。这里有两个伪函数显示了我正在尝试做的事情。

这是主要功能

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

void load(gsl_matrix * a);    

int main()
{
int row, col,i,j;   
row = 6; col = 25;
gsl_matrix *a = gsl_matrix_alloc(6,25);

load(a);

for (i = 0; i < 6; i++) 
  for (j = 0; j < 25; j++)
     printf ("a[%d,%d] = %g\n", i, j, 
         gsl_matrix_get (a, i, j));


return 0;
}   

这是从文件加载到矩阵中的加载函数。这部分似乎工作....我只是无法从这个函数得到结果到主函数。

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

#include <gsl/gsl_matrix.h>

void load(gsl_matrix * a)
{
int row_size, col_size;
row_size = 6; col_size = 25;    
int status_obs;
gsl_matrix * obs_map = gsl_matrix_alloc(row_size,col_size);

FILE *f = fopen("obs_map.dat","r");
status_obs = gsl_matrix_fscanf(f,obs_map);
fclose(f);

a = obs_map;    

if(status_obs == 0) 
    printf("Obstacle map loaded: %dx%d\n",row_size,col_size);

gsl_matrix_free (obs_map);

}

如果这是一个愚蠢的问题,我深表歉意,但我只需要在正确的方向上得到一点帮助。任何使用 GSL 的人的帮助将不胜感激。仅供参考,这里是gsl matrix examples

【问题讨论】:

    标签: c arrays function matrix gsl


    【解决方案1】:

    在从 load() 返回之前,您正在释放矩阵。也许最简单的方法是从 load() 返回一个 gsl_matrix*:

    gsl_matrix* load() {
    int row_size, col_size;
    row_size = 6; col_size = 25;    
    int status_obs;
    gsl_matrix * obs_map = gsl_matrix_alloc(row_size,col_size);
    
    FILE *f = fopen("obs_map.dat","r");
    status_obs = gsl_matrix_fscanf(f,obs_map);
    fclose(f);
    
    a = obs_map;    
    
    if(status_obs == 0) 
        printf("Obstacle map loaded: %dx%d\n",row_size,col_size);
    
    return obs_map;
    //Don't free it!
    //gsl_matrix_free (obs_map);
    
    }
    
    int main() {
    int row, col,i,j;   
    row = 6; col = 25;
    gsl_matrix *a = load();
    
    //load(a);
    
    for (i = 0; i < 6; i++) 
      for (j = 0; j < 25; j++)
         printf ("a[%d,%d] = %g\n", i, j, 
             gsl_matrix_get (a, i, j));
    
    //Now you can free it
    gsl_matrix_free(a);
    
    return 0;
    } 
    

    注意我没有编译这个,因为我没有尝试安装那个 GSL 库,所以如果它对你有用,那就太好了!

    【讨论】:

    • 是的,这基本上就是我所做的。感谢您的帮助!不习惯分配内存,但我在查看指针后意识到我在做什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 2013-02-15
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多