0

I am trying to set a array of structure in a array of structure. to this i have created a function. how ever i try it i am not able to do it.

struct polygon {
struct point polygonVertexes[100];
};
struct polygon polygons[800];
int polygonCounter = 0;


int setPolygonQuardinates(struct point polygonVertexes[]) {
    memcpy(polygons[polygonCounter].polygonVertexes, polygonVertexes,4);
}

int main(){

    struct point polygonPoints[100] = {points[point1], points[point2], points[point3], points[point4]};

    setPolygonQuardinates(polygonPoints);
    drawpolygon();
}



void drawpolygon() {
    for (int i = 0; polygons[i].polygonVertexes != NULL; i++) {
        glBegin(GL_POLYGON);
        for (int j= 0; polygons[i].polygonVertexes[j].x != NULL; j++)    {
            struct point pointToDraw = {polygons[i].polygonVertexes[j].x, polygons[i].polygonVertexes[j].y};
            glVertex2i(pointToDraw.x, pointToDraw.y);
        }
        glEnd();
    }
}

when i run this i get the following error

Segmentation fault; core dumped; real time
Naseeruddin V N
  • 597
  • 5
  • 17

1 Answers1

0

You cannot use strcpy here; that is for null-terminated strings. A struct is not a null-terminated string :) To copy objects around, use memcpy.

To pass arrays around in C, a second parameter stating the number of objects in the array is usually passed as well. Alternatively, the array and length are put into a struct, and that struct is passed around.

EDIT: An example of how to do this:

void setPolygonQuardinates(struct point* polygonVertexes, size_t polygonVertexesSize) {
    memcpy(polygons[polygonCounter].polygonVertexes, polygonVertexes, sizeof(point) * polygonVertexesSize);
}

int main(){
    struct point polygonPoints[100] = {points[point1], points[point2], points[point3], points[point4]};
                         /*     ^---------v   make sure they match */
    setPolygonQuardinates(polygonPoints, 100);
    drawpolygon();
}

If you need this explained, please ask. I think it is idiomatic C code.

  • i tried this but im still getting the same error. what else can i do to store the points array in the structure member array – Naseeruddin V N Apr 22 '17 at 15:35
  • thanks a lot for the help, That solved my problem. I am still learning to code and would love to know how to code better. – Naseeruddin V N Apr 22 '17 at 16:19
  • @NaseeruddinVN To do anything better you gotta keep practicing! Remember, all the experts here were beginners once. –  Apr 22 '17 at 16:22