Hello, i am writing a program to compute an integral... the values of x and f(x) are given in a file (2 columns, 10000 rows), i read from the file and then use the summation method to compute the integral. Command line arguments are used to get the upper limit
The program must allocate memory (i've used malloc), and use an external function to compute the intergral. The program compiles, but i get a segmentation error. I THINK THE PROBLEM IS IN THE EXTERNAL FUNCTION, because i blocked off the rest of the code with comments, and the segmentation error disappeared.
Please you could you describe in as much detail as you can where I am going wrong, as I am not very competent in C.
Thanks!!!
Code:
/****************************************************
** Module: C for Scientists 2010
** Student ID: 0915539
** PHUJEB
** Assignment 3
****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double integration(double, int);
int main(int argc, char* argv[])
{
FILE *input;
int ac=0, col, i, j, rec, ns;
float a, b;
const char inp_fn[]="px270prog3a.dat";
char buf[1025];
char *ch, *tokptr, *strptr=buf;
double *x, *fx, tmp, result;
input = fopen(inp_fn, "r");
if( argc != 2 ) /*Checking for the correct number of arguments, and showing user how to use correct format*/
{ printf("The upper limit was not entered correctly. Usage: %s UpperLimit\n", argv[0]);
exit(EXIT_FAILURE);
}
if(input == (FILE*) NULL)
{
printf("**** Error opening input file ****\n");
exit(EXIT_FAILURE);
}
else
{
b=atoi(argv[1]);
for (i = 0; i < 9999; i++)
{
fscanf(input, "%f %f", &x[i], &fx[i]); /*just added this bit to read the file, some later code may be unneccesary*/
}
fgets(buf, 1024, input);
while((tokptr=(char*)strtok(strptr, " \t\n\r\b,")) != NULL)
{
while(fscanf(input,"%lf",&tmp) == 1) ns++;
ns = ns / ac;
/* Now we know how big of an array to allocate */
x = (double*) malloc((ns+1)*sizeof(double));
fx = (double*) malloc((ns+1)*sizeof(double));
printf("Allocated memory for %d records\n",ns+1);
/* We have already read the file, so we will rewind
it to start from the top again */
rewind(input);
i=0; rec = 0;
while(fscanf(input,"%lf",&tmp) == 1)
{
j = (rec % ac) + 1;
if(j==1)
x[i] = (double)(tmp);
else if(j==2)
{
fx[i] = (double)(tmp);
i++;
}
rec++;
}
}
for(i=0; i<b; i++)
{
result = integration(fx, rec-1);
}
printf("The result of the integral is: %lf\n", &result);
fclose(input);
}
}
double integration(double data, int n)
{
int i;
double area, x[i], fx[i];
area = fx[i-1] * x[i] - x[i-1];
return(area);
}