2016-10-30 12 views
0

関数get_polyが実行されると、セグメント化エラーが発生します。プレースホルダーやものの中には、バグ修正の試みがありました。私は本当にこれを引き起こしているのか分かりません。配列へのポインタを使用する際のセグメンテーションエラー

//Weston Sapusek, cop3515 
//This program outputs the polynomial of a number given coefficients for each exponent. 

#include <stdio.h> 
#include <math.h> 

void get_poly(double *coeff, int N); 
void eval_poly(double *coeff, double base, int N); 

int main(void) 
{ 
    int N; //max exponent 
    double base; 

    printf("Please enter the power of your polynomial: "); 
    scanf("%d", &N); 

    printf("Please enter the base number: "); 
    scanf("%lf", &base); 

    double a[N]; 
    double *coeff; 
    coeff = &a[0]; 

    get_poly(coeff, N); 
    coeff = 0; //reset the coefficient pointer 

    eval_poly(coeff, base, N); 
    return 0; 
} 

void get_poly(double *coeff, int N) { 
    printf("Enter %d coeffecients of the function, in order: ", N); 
    int i = 0; 
    double placeholder; 
    for (i = 0; i < N; i++){ 
     scanf("%lf", &placeholder); 
     *coeff = placeholder; 
     coeff++; 
    } 
} 

void eval_poly(double *coeff, double base, int N) 
{ 
    int i = 0; 
    double x = 0; //total 

    for (i = 0; i < N; i++){ 
     x+= *coeff * base; 
    } 
    printf("%lf", x); 
} 
+0

コンパイルしますか?ダブルa [N];ここでNは一定でなければならない – Asesh

+2

このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –

+0

@Asesh:GCCでデフォルトでC++の拡張機能として使用できるC99の不思議な機能であるVariable Length Arrayです。 –

答えて

0

これは、問題のあるコードのようになります。そのcoeffがNULLの後

get_poly(coeff, N); 
coeff = 0; //reset the coeffecient pointer 

eval_poly(coeff, base, N); 

あなたは、coeffecientポインタをリセット。次に、eval_polyを呼び出して、eval_poly関数内のNULLポインタcoeffを参照解除します。それがセグメンテーションの原因となった。

0

ちょうどこの行を削除します。それは価値によって送られているため(それはポインタだが)

coeff = 0; //reset the coeffecient pointer 

coeffget_polyによって変更されないcoeff = 0;を設定

は、それが無効なメモリアドレスを指すことができます。

関連する問題