0

I have some code like (I've simplified it a bit):

# define NUMBER_OF_PARTICLES 1

typedef struct {
    Axes velocity;      // struct with x,y,z floats
} Particle;

Particle * array_of_particles;

Particle create(Particle p) {
    p.velocity.x = 0.0f;
    p.velocity.y = 0.0f;
    p.velocity.z = 0.0f;

    return p;
}

void create_particles() {
    array_of_particles = (Particle *) malloc(sizeof(Particle) * NUMBER_OF_PARTICLES);

    int p;      
    for (p = 0; p < NUMBER_OF_PARTICLES; p++) { 
        Particle current_particle = array_of_particles[p];
        array_of_particles[p] = create(current_particle);
    }
}

Hopefully you can see that I am trying to make the array element at index p be the struct of the current_particle. I think I am misunderstanding how to do this as it returns 0 when I print array_of_particles[p]. Could someone guide me as to the correct way of achieving this?

3
  • What's actually wrong with that code ? Commented Dec 5, 2013 at 11:44
  • 1
    Please don't cast the return value of malloc() in C. Commented Dec 5, 2013 at 12:09
  • @unwind oh I had noticed this when looking at examples online, but it hadn't really clicked at the difference between the forms. Thanks for pointing it out. Commented Dec 5, 2013 at 12:20

1 Answer 1

4

try

void create_particles() 
{
  array_of_particles 
    = (Particle *) malloc(sizeof(Particle)*NUMBER_OF_PARTICLES);

  int p;      
  for (p = 0; p < NUMBER_OF_PARTICLES; p++) { 
    Particle* current_particle = array_of_particles + p;
    create(current_particle);
  }
}

and change

void create(Particle* p) 
{
  p->velocity.x = 0.0f;
  p->velocity.y = 0.0f;
  p->velocity.z = 0.0f;
}

what you did was to pass a copy of the argument to the function so the changes never left the function.

there is also no need to return the Particle and then copy it, you already are passing the struct to the function so you can modify it by using the argument 'p'.

Sign up to request clarification or add additional context in comments.

6 Comments

ahhh so I reference the particle and then create pointers to it. Cool, thanks!
I get this error: error: incompatible types when initializing type ‘struct Particle *’ using type ‘Particle’ at this line: Particle* current_particle = array_of_particles[p];
Try this, Particle current_particle = array_of_particles[p]; create(&current_particle);
@claptrap can you explain how the array_of_particles + p works?
It's the address of entry p in your array (base address plus p times the size of a Particle because it's a Particle*). Another way of writing it would be &array_of_particles[p].
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.