2014-01-06 21 views
1

在我的項目初​​始化,我已創建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; 

正如你可能已經注意到,類型StructureTriangle 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添加到當前StructureS = 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用三角形T1T2,然後我使用S = addTriangle(T3,S)的結果將是一個Structure用下面的Triangle列數組:{T?,T2,T3},其中T?顯然已經隨機值。

這是怎麼發生的?

回答

1
while(i++<S.nt) R[0].triangles[i] = S.triangles[i]; 

應該像

for (i=0; i<S.nt; i++) { 
    R.triangles[i] = S.triangles[i]; 
} 

目前,你跳過分配的R.triangles第一個元素,通過讀取超出S.triangles末分配倒數第二個元素。你可以通過推遲遞增i來解決這個問題,直到每個循環結束。 (你可以繼續這樣使用while循環做,我發現了一個for循環更加清晰。)

此外,所有使用R[0]可以(應該)被R取代。 R是一個單一的結構,而不是一個數組。