2012-03-12 68 views
0

我遇到了意想不到的行爲,我寫了一個函數來計算一組3D點的平均點。非靜態變量的累積返回值?

static inline Point3d 
average_vertex_position(Vertex vertices[], int nPoints) 
{ 
    Point3d average = { 0.0, 0.0, 0.0 }; // Must be there to avoid accumulation 
    Point3d point; 
    int i; 

    for (i = 0; i < nPoints; i++) 
    { 
    point = vertices[i].position; 
    average.x += point.x; 
    average.y += point.y; 
    average.z += point.z; 
    } 

    average.x /= (double) nPoints; 
    average.y /= (double) nPoints; 
    average.z /= (double) nPoints; 

    return average; 
} 



// ... 
Point3d average; 
// ... 
for (j = i; j < nVertices; j++) 
{ 
    // ... 
    average = average_vertex_position(vertices, nVertices); 
    // ... 
} 

每次迭代的average_vertex_position返回值會累積,除非我明確添加初始化Point3d average = { 0.0, 0.0, 0.0 };

如果之前的返回值爲Point3d(10, 0, 20),並且下一次運行應返回Point3d(20, 10, 0),它將返回累計結果Point3d(30, 10, 20)

本來我只是Point3d average;假設所有的成員值(double值)將被初始化爲0.0。我還假定average將在每次通話之間處於初始狀態。我不明白爲什麼我需要明確地初始化它?

我修剪了我認爲不相關的代碼 - 但我可能是錯的,在這種情況下,如果它沒有足夠的信息,我會更新。

回答

3

這是正常的auto變量 - 如果沒有明確說明,它們不會被初始化爲0。

舊值重用的事實純屬巧合,因爲您沒有任何其他函數調用。如果你有他們,在給定的堆棧位置的內存將被覆蓋,你的值是不同的。

+0

那麼當我讀到C和變量時,有些東西是錯過了的。我認爲'int'和'double'總是被初始化爲0.清晰明確的開始是最安全的。 – thomthom 2012-03-12 13:06:42

+0

是否可以在其定義中定義一個'struct'的默認值 - 或者每次創建一個變量時,我都必須這樣做嗎? – thomthom 2012-03-12 13:07:49

+0

有一種感覺,這是一個n00b問題... – thomthom 2012-03-12 13:08:11