dgBP
dgBP

Reputation: 1691

Put a struct into an array element in C

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?

Upvotes: 0

Views: 4658

Answers (1)

AndersK
AndersK

Reputation: 36082

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'.

Upvotes: 4

Related Questions