簡體   English   中英

如何定義全局gsl_vector

[英]How to define a global gsl_vector

有人可以幫我解決這個問題嗎? 我有這個簡單的代碼:

#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

謝謝你的幫助

那是因為您兩次聲明了變量Cell 請替換gsl_vector * Cell = gsl_vector_alloc(LENGTH_Cell); 只需Cell = gsl_vector_alloc(LENGTH_Cell); 另外,不要忘記使用gsl_vector_free (Cell);正確釋放內存gsl_vector_free (Cell); 經過所有的計算。 現代編譯器很聰明,但是,它們並不總是能抓住這么小的事情(我曾經花了大約一個星期的時間來解決類似的問題)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM