I need some help with a program I am writing which reads type double vertices from a text file, then computes and prints the perimeter of the resultant polygon.
Every time i compile and run it, everything seems to be ok until i hit the for statement, which triggers a seg fault. Beyond that, there is probably a bigger problem, but i cannot see it.
edit: I also found another thread with a very similar topic, but even after completely duplicating the resulting program, it still gave incorrect values.
Code:
#include <stdio.h>
#include <math.h>
typedef struct {double x, y;} vertex_t;
double dist(vertex_t a, vertex_t b);
int main(void) {
FILE *fp;
char name[64];
double perim = 0,x,y;
vertex_t verts[20];
vertex_t buffer;
int i = 0,j = 0,max = 0,status = 1;
printf("Enter the file name: ");
scanf("%s",name);
fp = fopen(name,"r");
while (status != EOF) {
status = fscanf(fp," %lf %lf ",&x, &y);
buffer.x = x;
buffer.y = y;
verts[i] = buffer;
i++;
max++;
}
for (i = 0;i < max;j++) {
perim += dist(verts[j],verts[j+1]);
}
perim += dist(verts[0],verts[max]);
printf("The perimeter is %.3lf\n",perim);
return 0;
}
double dist(vertex_t a, vertex_t b) {
return sqrt(pow(b.x-a.x,2)+pow(b.y-a.y,2));
}