[英]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; 您不能在这里使用
strcpy
。 that is for null-terminated strings. 这是针对以null终止的字符串。 A
struct
is not a null-terminated string :) To copy objects around, use memcpy
. struct
不是以Null结尾的字符串:)要复制对象,请使用memcpy
。
To pass arrays around in C, a second parameter stating the number of objects in the array is usually passed as well. 为了在C中传递数组,通常也要传递第二个参数,该参数说明数组中的对象数。 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.
我认为这是惯用的C代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.