如何定义全局gsl_vector

时间:2018-12-29 14:11:22

标签: c gsl

有人可以帮助我解决这个问题吗?我有这个简单的代码:

#include "prova.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_pow_int.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_vector.h>

/* Global structures */
#define LENGTH_Cell 1001
gsl_vector * Cell; /* Global definition */

/* Function */
double sum(int l){
    double sum = 0;

    for(int j=0; j<l; j++)
    {
        sum = sum + gsl_vector_get(Cell, j);
    }

    return sum;
}

int main() {

    gsl_vector * Cell = gsl_vector_alloc(LENGTH_Cell);

    FILE *Cl_in = fopen("C_ells_1000.dat","r");
    gsl_vector_fscanf(Cl_in, Cell);
    fclose(Cl_in);

    for (int i = 0; i < 5; i++)
    {
        printf("sum: %g \n", sum(i));
    }

    return 0;
}

程序会编译,但是当我运行程序时,会显示以下输出:

sum: 0 
Segmentation fault: 11

我认为问题是我没有以正确的方式定义全局gsl_vector单元。 你有什么建议吗?

更多信息。 这是“ C_ells_1000.dat”的内容

0.
0.
1.48889036806174737e-10
6.99975015453780434e-11
3.9538692950311228e-11
2.51360836766398574e-11
1.73497511436282967e-11
1.27165467072195804e-11
9.75002071723029932e-12
7.7432773162174558e-12
6.3213378366797444e-12
5.27764322481988366e-12

文件“ prova.h”如下:

#ifndef prova_h
#define prova_h

#include <stdio.h>

#endif /* prova_h */

要编译程序,请使用命令

gcc -o prova prova_1.c -I /usr/local/include -lm -lgsl -lgslcblas

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

那是因为您两次声明了变量Cell。 请仅将gsl_vector * Cell = gsl_vector_alloc(LENGTH_Cell);替换为Cell = gsl_vector_alloc(LENGTH_Cell); 此外,在完成所有计算后,请不要忘记使用gsl_vector_free (Cell);正确释放内存。现代编译器很聪明,但是,它们并不总是能抓住这么小的事情(我曾经花了大约一个星期的时间来解决类似的问题)。

相关问题