2009-04-29 37 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