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

我面临的问题是,当我真正需要时,它看起来不像是在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;
};

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

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;        
    }
}

然后在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);
    }
}

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

有帮助吗?

解决方案

问题在于这个定义:

struct particle particles[];

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

您可以尝试使用 max_particles ,但我不确定在C定义中使用变量(尽管 const )是合法的。

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

#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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top