将struct数组作为参数传递给函数

时间:2017-04-22 14:49:52

标签: c pointers struct c99 function-parameter

我试图在结构数组中设置一个结构数组。对此我创建了一个函数。我怎么尝试它我无法做到这一点。

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();
    }
}

当我运行此操作时,我收到以下错误

Segmentation fault; core dumped; real time

1 个答案:

答案 0 :(得分:0)

你不能在这里使用struct;这是针对以null结尾的字符串。 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(); } 不是以空字符结尾的字符串:)要复制对象,请使用memcpy

要在C中传递数组,通常也会传递说明数组中对象数的第二个参数。或者,将数组和长度放入结构中,并传递该结构。

编辑:如何执行此操作的示例:

calc.l

如果您需要解释,请询问。我认为这是惯用的C代码。