문제

나는 기본적인 구체를 시뮬레이션하기 위해 응용 프로그램을 구축하려고합니다.

내가 직면하고있는 문제는 실제로 필요할 때 데이터가 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;
};

배열을 생성하고 입자를 할당하는 초기화 방법이 있습니다.

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[];

메모리를 예약하는 것이 아니라 빈 배열을 정의하는 것입니다. 당신은 그 사각형 괄호에 무언가를 넣어야합니다. 이 배열의 다양한 위치에 대한 모든 글이 Segfault 충돌을 일으키지 않았다는 것은 놀라운 일입니다 ...

당신은 함께 시도 할 수 있습니다 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