| structures/polygon.c - En struct med en pointer til et array af hjørne-punkter i en polygon. | Lektion 12 - slide 22 : 36 Program 3 |
#include <stdio.h>
#include <stdlib.h>
struct point {
double x, y;
};
typedef struct point point;
struct polygon {
int rank;
point *points;
};
typedef struct polygon polygon;
polygon make_polygon(int rank, point corners[]){
int i;
struct polygon result;
result.rank = rank;
result.points = (point*)malloc(rank * sizeof(struct point));
// Check if malloc returns NULL - not included here...
for(i = 0; i < rank; i++)
result.points[i] = corners[i];
return result;
}
int main(void) {
polygon a_pentagon;
point five_points[] = { {0.0, 0.0}, {3.0, 7.0}, {10.0, 5.0}, {10.0, -5.0}, {2.0, -16.0} };
a_pentagon = make_polygon(5, five_points);
// ...
// Free memory allocated for a_pentagon.points ...
printf("Size of polygon: %d bytes\n", sizeof(polygon));
printf("Size of int: %d bytes\n", sizeof(int));
printf("Size of point*: %d bytes\n", sizeof(point * ));
return 0;
}