2017-04-22 170 views
0

我想在结构数组中设置结构数组。为此我创建了一个函数。我怎么试试它,我无法做到这一点。将结构数组作为参数传递给函数

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 
+0

“我无法做到这一点是什么意思?” – OldProgrammer

+0

此代码的任何特定错误? – Gaurav

+0

对不起的英语感到抱歉。我的意思是我无法将polygonPoints数组复制到polygon结构的polygonVertexes成员中。 setPolygonQuardinates函数执行后,polygonVertexes成员具有垃圾值。 –

回答

0

你不能在这里使用strcpy;那是以空字符结尾的字符串。 A struct不是以空字符结尾的字符串:)要复制周围的对象,请使用memcpy

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

编辑:如何做到这一点的一个例子:

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

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

+0

我试过这个,但我仍然得到相同的错误。我还能做些什么来将点数组存储在结构成员数组中 –

+0

我已经用一个例子编辑了我的答案。 – InternetAussie

+0

非常感谢您的帮助,解决了我的问题。我仍然在学习编码,并且很想知道如何更好地编写代码。 –