-1

i wrote this program which calculates 8 polynomial degrees at value of x inputted by the user. the program runs, however once i enter the 8 polynomials it should allow me to enter the value of x however it skips, and shows me the output. i tried using floats and doubles in scanner function however that didn't work. any help would be greatly appreciated, thank you.

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

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

int main(void)
{
    int N = 8;
    double res;
    double base = 0.0;
    double a[N];
    double *coeff;
    coeff = &a[0];

       printf("Enter the eight coeffecients: \n");
       scanf(" %d",&N);
       get_poly(coeff, N);

       printf("Enter x: \n");
       scanf(" %lf", &base);

       res=eval_poly(coeff, base, N);

       printf("Output: %f. \n",res); 


      return 0;
  }

void get_poly(double *coeff, int N)
{
   int i = 0;
   double placeholder;
   for (i = 0; i < N; i++)
   {
    scanf(" %lf", &placeholder);
    *coeff = placeholder;
    coeff++;
   }
}

double eval_poly(double *coeff, double base, int N)
{
   int i = 0;
   double res=0.0;

   for (i = 0; i < N; i++)
   res=res+coeff[i]*pow(base,i);

   return res;
}
corvo
  • 11
  • 1
  • 5
  • Possible duplicate of [Scanf skips second line of input, always](http://stackoverflow.com/questions/32958993/scanf-skips-second-line-of-input-always) – David Hoelzer Mar 26 '17 at 10:14

1 Answers1

0

A major problem is this definition in the eval_poly function:

double res=coeff[N];

Here the value of N is the size of the array passed to the function. Using it as an index will be out of bounds and lead to undefined behavior.

Same thing with the loop, where the condition i <= N will lead to you index the array out of bounds. And you will count the same element twice.

You should probably initialize res to zero.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621