1

I'm trying to copy to a dynamically-allocated array in C (The source array may or may not be dynamically allocated. The first element of the array is copied correctly, but the rest is not. Can anyone tell what I'm doing wrong?

Here's where I'm calling the method:

vec3 tempVel = {
    (float)rand()/(float)RAND_MAX * (2.0f * INIT_VELOCITY_DIMENSION_MAGNITUDE) - INIT_VELOCITY_DIMENSION_MAGNITUDE,
    (float)rand()/(float)RAND_MAX * (2.0f * INIT_VELOCITY_DIMENSION_MAGNITUDE) - INIT_VELOCITY_DIMENSION_MAGNITUDE,
    (float)rand()/(float)RAND_MAX * (2.0f * INIT_VELOCITY_DIMENSION_MAGNITUDE) - INIT_VELOCITY_DIMENSION_MAGNITUDE
};
thisBoid->velocity = copyArrays2(&tempVel, 3);

And the method:

vec3* copyArrays2(vec3 *src, int len){

    vec3 *tempArray = (vec3*)malloc(len*sizeof(vec3));
    for(int i=0; i<len; i++){
        *tempArray[i] = *src[i];
    }

    return tempArray;
}

Printing the values of 'tempVel' before copying and 'thisBoid->velocity' afterwards gives the following output:

{0.895216, -0.107424, 0.532019}
{0.895216, 10.000000, 0.500000}
jtruskow
  • 29
  • 5

1 Answers1

1

*tempArray[i] is the first element of the i'th vec3.

Operator precedence makes that it is evaluated *(tempArray[i]) , i.e. tempArray[i][0]. Only the first element of each vec3 is touched. If vec3 is a plain array in disguise you'll have to iterate through its elements in an inner loop.

Example code, provided typedef float vec3[3];:

for(int i=0; i<len; i++){
   for(int ii=0; ii<3; ii++){
        tempArray[i][ii] = src[i][ii];
    }
}

Btw, I would like to use this opportunity to thank iharob for his constructive comments.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62