使用OpenGL和GLFW操作C数组

Mal*_*chi 1 c opengl glfw

我正在尝试构建一个应用程序来模拟一些基本的球体移动.

我面临的问题是,当我真正需要时,它看起来不像是在init语句之外的数组中分配数据.这与我声明包含粒子的数组的方式有关.

我想创建一个结构数组,可以从各种方法访问,所以在我的文件顶部下面我使用的include语句:

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;
};
Run Code Online (Sandbox Code Playgroud)

我有一个初始化方法,它创建数组并为其分配粒子

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;        
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在draw方法内部绘制设置场景的方法

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码http://pastebin.com/m131405dc的副本

unw*_*ind 5

问题是这个定义:

struct particle particles[];
Run Code Online (Sandbox Code Playgroud)

它不是保留任何内存,只是定义一个空数组.你需要在方括号中放一些东西.你对这个阵列中不同位置的所有写作都没有导致段错误崩溃,这真是一个奇迹......

您可以试试max_particles,虽然我不确定const在C定义中使用变量(尽管是一个)是合法的.

经典的解决方案是使用预处理器,如下所示:

#define MAX_PARTICLES 50

struct particle particles[MAX_PARTICLES];
Run Code Online (Sandbox Code Playgroud)

然后在各种循环中使用MAX_PARTICLES.我建议改为将文字放在括号中:

struct particle particles[50];
Run Code Online (Sandbox Code Playgroud)

然后写这样的循环:

for(i = 0; i < sizeof particles / sizeof *particles; i++)
Run Code Online (Sandbox Code Playgroud)

这是一个编译时的部门,所以它不会让你付出任何代价,而你正在重新使用定义本身来提供数组中的元素数量,这些(IMO)是优雅的.您当然可以采取一些中间方式并定义一个新的宏,如下所示:

#define MAX_PARTICLES  (sizeof particles / sizeof *particles)
Run Code Online (Sandbox Code Playgroud)