C 函数中初始化的结构行为异常
在我的项目中,我创建了3种不同的C 函数中初始化的结构行为异常,c,function,struct,C,Function,Struct,在我的项目中,我创建了3种不同的typedef struct类型: typedef struct Point { float x; float y; float z; } Point; typedef struct Triangle { Point A; Point B; Point C; unsigned char color[3];//RGB } Triangle; typedef struct Structure {
typedef struct
类型:
typedef struct Point
{
float x;
float y;
float z;
} Point;
typedef struct Triangle
{
Point A;
Point B;
Point C;
unsigned char color[3];//RGB
} Triangle;
typedef struct Structure
{
Triangle* triangles;
unsigned int nt; //number of triangles in array
} Structure;
正如您可能已经注意到的,类型结构
有一个动态大小的三角形数组
s,因此我还将在这里发布内存分配和释放函数:
Structure newStructure(unsigned int nt)
{
Structure S;
Triangle* tri = malloc ((nt) * sizeof(Triangle));
if (tri!=NULL)
{
S.triangles = tri;
S.nt = nt;
}
else S.nt = 0;
return S;
}
void delStructure (Structure S)
{
if (S.triangles != NULL) free (S.triangles);
}
然后,我想创建一个函数,使用以下语法将三角形添加到当前结构中:S=addTriangle(T,S)
。这就是我所拥有的:
Structure addTriangle(Triangle T, Structure S)
{
Structure R = newStructure(S.nt+1);
int i=0;
while(i++<S.nt) R[0].triangles[i] = S.triangles[i];
R[0].triangles[S.nt] = T;
delStructure(S); //Is this necessary?
return R[0];
}
结构添加三角形(三角形T,结构S)
{
结构R=新结构(S.nt+1);
int i=0;
while(i++while(i++
while(i++<S.nt) R[0].triangles[i] = S.triangles[i];
for (i=0; i<S.nt; i++) {
R.triangles[i] = S.triangles[i];
}