2009-04-29 75 views
1

我正試圖構建一個應用程序來模擬一些移動的基本球體。使用OpenGL和GLFW處理C數組

我面臨的問題是,它看起來不像是在我真正需要的時候將數據分配給init語句之外的數組。這與我聲明包含粒子的數組的方式有關。

我想創建可以從各種方法來訪問結構數組所以在我已經使用了包括以下聲明我的文件的開頭:

struct particle particles[]; 


// Particle types 
enum TYPES { PHOTON, NEUTRINO }; 

// Represents a 3D point 
struct vertex3f 
{ 
    float x; 
    float y; 
    float z; 
}; 

// Represents a particle 
struct particle 
{ 
    enum TYPES type; 
    float radius; 
    struct vertex3f location; 
}; 

我有創建數組的INITIALISE方法和分配顆粒它

void init(void) 
{ 
    // Create a GLU quadrics object 
    quadric = gluNewQuadric(); 
    struct particle particles[max_particles]; 

    float xm = (width/2) * -1; 
    float xp = width/2; 
    float ym = (height/2) * -1; 
    float yp = height/2; 

    int i; 
    for (i = 0; i < max_particles; i++) 
    { 
     struct particle p; 

     struct vertex3f location; 
     location.x = randFloat(xm, xp); 
     location.y = randFloat(ym, yp); 
     location.z = 0.0f; 

     p.location = location; 
     p.radius = 0.3f; 

     particles[i] = p;   
    } 
} 

然後平局方法內繪製集場景的方法

// Draws the second stage 
void drawSecondStage(void) 
{ 

    int i; 

    for (i = 0; i < max_particles; i++) 
    { 
     struct particle p = particles[i]; 

     glPushMatrix(); 
     glTranslatef(p.location.x , p.location.y, p.location.z); 
     glColor3f(1.0f, 0.0f, 0.0f); 
     gluSphere(quadric, 0.3f, 30, 30); 
     glPopMatrix(); 

     printf("%f\n", particles[i].location.x); 
    } 
} 

這裏是我的代碼http://pastebin.com/m131405dc

回答

5

問題副本是這樣的定義:

struct particle particles[]; 

它不保留任何內存,僅僅定義一個空數組。你需要把東西放在方括號中。這是一個奇蹟,你在這個陣列中的各個位置的所有寫入沒有導致段錯誤崩潰...

你可以嘗試max_particles,雖然我不確定使用變量(雖然const之一)是合法的C的定義。

傳統的解決方案是使用預處理器,就像這樣:

#define MAX_PARTICLES 50 

struct particle particles[MAX_PARTICLES]; 

然後在各個循環使用MAX_PARTICLES。我建議,而不是把字面括號:

struct particle particles[50]; 

然後編寫循環是這樣的:

for(i = 0; i < sizeof particles/sizeof *particles; i++) 

這是一個編譯時分,所以它不會花費你任何東西,你重新使用定義本身來提供數組中元素的數量,哪個(IMO)是優雅的。您當然可以採取一些中間的方式,並定義一個新的宏,如下所示:

#define MAX_PARTICLES (sizeof particles/sizeof *particles) 
+0

非常感謝您的回答 - 並深入您的工作。 謝謝! – Malachi 2009-04-29 11:53:29