flexible length struct array inside another struct using C

Posted by renz on Stack Overflow See other posts from Stack Overflow or by renz
Published on 2010-03-12T02:30:21Z Indexed on 2010/03/12 2:37 UTC
Read the original article Hit count: 527

Filed under:
|
|

Hi I am trying to use C to implement a simple struct:
2 boxes, each contains different number of particles; the exact number of particles are passed in main().

I wrote the following code:

typedef struct Particle{
    float x;
    float y;
    float vx;
    float vy;
}Particle;

typedef struct Box{
    Particle p[];
}Box;

void make_box(Box *box, int number_of_particles);

int main(){
    Box b1, b2;
    make_box(&b1, 5);  //create a box containing 5 particles
    make_box(&b2, 10); //create a box containing 10 particles
}

I've tried to implement make_box with the following code

void make_box(struct Box *box, int no_of_particles){
    Particle po[no_of_particles];
    po[0].x = 1;
    po[1].x = 2;
    //so on and so forth...
    box->p = po;
}

It's always giving me "invalid use of flexible array member". Greatly appreciated if someone can shed some light on this.

© Stack Overflow or respective owner

Related posts about c

    Related posts about struct