简体   繁体   中英

passing struct array as parameter to a function

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM