Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to copy an array

So at the end of each iteration that I'm doing, I want to make my array be equal to my new array (which I have called array_new). I want every element of array to take the same value as is in array_new but I'm interested in getting my code as quick as possible and so copying everything across element-by-element as this current code does isn't an option:

for(i=0;i<N_a;i++) {
  for(j=0;j<N_b;j++) {
    array[i][j] = array_new[i][j];
  }
}

This takes quite a long time because my values of N_a and N_b are very large. Is there a way to simply change what each of them point to so that I can start my next iteration more quickly? I've tried doing stuff like

 double *temp = *array;
 *array = *array_new;
 *array_new = temp;

in order to try and avoid a slow element-by-element copying procedure but it doesn't seem to work for me. Effectively what I'm trying to make happen is for every element of array point to the corresponding element in array_new but I can't work out how to make the pointers do that.

Any help would be much appreciated!

like image 832
thay2302 Avatar asked Oct 27 '25 15:10

thay2302


2 Answers

Since the memory size of your array is fixed, you can simply copy the memory block from one pointer to the other. It doesn't get any faster than that.

In c/c++ you could use memcpy if that is the language you are using. Every language has something equivalent.

Edit: since you confirmed use of c I can get more detailed:

memcpy(array_new,array,sizeof(VARIABLE_TYPE_of_ARRAY_ELEMENT)*N_a*N_b);
like image 145
SunKnight0 Avatar answered Oct 30 '25 05:10

SunKnight0


Your pointer-swap code is just a little bit off: you are dereferencing your pointers where you shouldn't. After all, the point of that code is to avoid copying data by just swapping two pointers. Here are the correct versions (depending on whether you use a true 2D array or an array of pointers to arrays):

//array is declared as
double (*array)[N_b];

double (*temp)[N_b] = array;
array = array_new;
array_new = temp;

or

//array is declared as
double** array;

double** temp = array;
array = array_new;
array_new = temp;

This is all you need, and it's definitely the fastest possible way to exchange contents of two buffers. Much faster than memcpy()...

like image 38
cmaster - reinstate monica Avatar answered Oct 30 '25 05:10

cmaster - reinstate monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!