質問

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

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

役に立ちましたか?

解決

問題はこの定義です:

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top