在我的項目初始化,我已創建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
{
Triangle* triangles;
unsigned int nt; //number of triangles in array
} Structure;
正如你可能已經注意到,類型Structure
有Triangle
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);
}
後來想使用下面的語法做一個函數將Triangle
添加到當前Structure
: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];
}
它編譯時沒有顯示錯誤信息,但是當我使用的功能,陣列上的第一Triangle
獲取隨機值。 更清楚,如果我有所述陣列中的Structure S
用三角形T1
和T2
,然後我使用S = addTriangle(T3,S)
的結果將是一個Structure
用下面的Triangle
列數組:{T?,T2,T3}
,其中T?
顯然已經隨機值。
這是怎麼發生的?