[英]passing struct array as parameter to a function
我試圖在結構數組中設置一個結構數組。 為此,我創建了一個功能。 我怎么嘗試過,我都做不到。
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
您不能在這里使用strcpy
。 這是針對以null終止的字符串。 struct
不是以Null結尾的字符串:)要復制對象,請使用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代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.