1

動き回るいくつかの基本的な球をシミュレートするアプリケーションを構築しようとしています。

私が直面している問題は、実際に必要なときに、データが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;        
    }
}

次に、描画メソッドの内部で、設定されたシーンを描画するメソッド

// 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

4

1 に答える 1

5

問題はこの定義です:

struct particle particles[];

空の配列を定義するだけで、メモリを予約するのではありません。それらの角かっこに何かを入れる必要があります。この配列のさまざまな位置へのすべての書き込みがセグメンテーション違反のクラッシュを引き起こしていないのは不思議です...

max_particles変数を使用することは(const1つではありますが)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)
于 2009-04-29T11:41:01.990 に答える