Hi, I just had a go at starting on a program. It makes 2 points which seems to work until I try and print the data at which point it segfaults. Heres my main:
vector.h:Code:#include <stdio.h> #include "vector.h" int main() { Polygon *line; NewLine(line, 10, 10, 20, 20); PrintPoints(line); DeletePolygon(line); return 0; }
and vector.c:Code:#include <stdlib.h> #include <stdio.h> #define true 1 #define false 0 #ifndef Uint8 #define Uint8 unsigned char #endif #ifndef Uint32 #define Uint32 unsigned long #endif #define POLYGON_IS_SPLINE 128 #define POLYGON_SPLINE_IS_CUBIC 64 //Must be spline to be cubic #define POLYGON_IS_CLOSED 32 #define POLYGON_IS_FILLED 16 //Must be closed to be filled and have size > 2 typedef struct { int x, y; // Point position float vx, vy; // Independant point velocity }Point; typedef struct { Uint8 flags; Uint32 size; Point *point; // List of points float vx, vy; // Polygon velocity }Polygon; int DeletePolygon(Polygon *p); int NewPoint(Point *p, int x, int y); int NewLine(Polygon *p, int x1, int y1, int x2, int y2); void PrintPoints(Polygon *poly);
Its segfauting somewhere in the red, but that could be because I havent created my structs propery or something. What am I doing wrong?Code:#include "vector.h" int NewPoint(Point *p, int x, int y) { p = malloc(sizeof(Point)); if(p == NULL) return false; p->x = x; p->y = y; return true; } int NewLine(Polygon *p, int x1, int y1, int x2, int y2) { p = malloc(sizeof(Polygon)); if(p == NULL) return false; p->size = 2; p->flags = 0; p->point = malloc(sizeof(int*)*2); Point *temp = p->point; if( NewPoint(temp, x1, y1) == false) { free(p); return false; } temp++; if( NewPoint(temp, x2, y2) == false) { free((--temp)); free(p); return false; } return true; } void PrintPoints(Polygon *poly) { Point *p = poly->point; for(int i=0; i<poly->size; i++, p++) printf("%c(%d, %d)\n", 'A'+i, p->x, p->y); } int DeletePolygon(Polygon *p) { Point *temp = p->point; for(int i=0; i < p->size; i++, temp++) free(temp); return true; }
Cheers.


