当运行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 :(得分:0)
这看起来像有问题的代码:
get_poly(coeff, N);
coeff = 0; //reset the coeffecient pointer
eval_poly(coeff, base, N);
在<{1}}为NULL之后,您重置系数指针。然后调用coeff
并取消引用eval_poly
函数内的NULL指针coeff
。这导致了段错误。
答案 1 :(得分:0)
只需删除此行:
coeff = 0; //reset the coeffecient pointer
coeff
未被get_poly
更改,因为它是按值发送的(尽管它是指针)
设置coeff = 0;
使其指向无效的内存地址。