I have these two structs, everything goes well, but when I try calculating poly->scope
The output is 0.0 , like nothing really happens.
Also, I get some errors I cannot understand, for example -
the line scanPoint(&poly->points[i]);
says "Dereferencing NULL pointer"
Thanks for help.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct point
{
int x, y;
}point;
typedef struct polygon
{
int n;
point* points;
double scope;
}polygon;
void scanPoint(point*);
void scanPolygon(polygon*);
double distance(point*, point*);
void calculatePolygonScope(polygon*);
void freeMemory(polygon*);
int main()
{
polygon poly;
scanPolygon(&poly);
calculatePolygonScope(&poly);
freeMemory(&poly);
printf("Output: Scope of polygon: %.2lf\n", poly.scope);
return 0;
}
void scanPoint(point* p)
{
printf("Please Enter X of your point: \n");
scanf("%d", &p->x);
printf("Please Enter Y of your point: \n");
scanf("%d", &p->y);
}
void scanPolygon(polygon* poly)
{
int i;
printf("Please enter how many points does the polygon have? : \n");
scanf("%d", &poly->n);
poly->points = (point*)calloc(poly->n, sizeof(point));
for (i = 0; i < poly->n; i++)
{
scanPoint(&poly->points[i]);
}
}
double distance(point* p1, point* p2)
{
double x = pow(((double)p2->x - (double)p1->x), 2);
double y = pow(((double)p2->y - (double)p1->y), 2);
double dis = sqrt(x + y);
return dis;
}
void calculatePolygonScope(polygon* poly)
{
int i;
double temp = 0.0;
for (i = 0; i < poly->n-1;)
{
temp += distance(&poly->points[i], &poly->points[++i]);
}
poly->scope = temp;
}
void freeMemory(polygon* poly)
{
free(poly->points);
}