2

I have an array with it the first x_size*y_size values filled, and now I need to duplicate them DATA_JUMP times in the same array in later memory.

for(int i=1; i < DATA_JUMP; i++)
 for(int k = 0; k < x_size*y_size; k++)
  orig_depth[k + i*x_size*y_size] = orig_depth[k];

This works like I want it to, however this may slow down on large datasets. I wonder if there is a trick to do this with a little pointer arithmetic.

Andre Kampling
  • 5,476
  • 2
  • 20
  • 47
Kev1n91
  • 3,553
  • 8
  • 46
  • 96
  • 5
    `memcpy(orig_depth + i*x_size*y_size, orig_depth, x_size*y_size * sizeof *orig_depth);` instead of the inner loop. – mch Aug 04 '17 at 08:52
  • Thank you, works like a charm - do you want to give it as an answer so I can accept it? – Kev1n91 Aug 04 '17 at 08:58

1 Answers1

3

You can use

memcpy(orig_depth + i*x_size*y_size, orig_depth, x_size*y_size * sizeof *orig_depth);

instead of the inner loop. You have to be sure that i*x_size*y_size is not 0, because in this case the pointer would overlap.

sizeof *orig_depth is the size of 1 element of the array, while sizeof orig_depth is the size of the whole array.
for int orig_depth[100]; sizeof *orig_depth is sizeof(int) and sizeof orig_depth is 100 * sizeof(int).

The advantage of sizeof *orig_depth against sizeof(int) is, that you can change the type without the requirement of changing every sizeof. The best pratice name for this is: Single source of Truth https://en.wikipedia.org/wiki/Single_source_of_truth

mch
  • 9,424
  • 2
  • 28
  • 42
  • 1
    One question what does sizeof *orig_depth means in comparison to sizeof(orig_depth) ? Coud you please elaborate – Kev1n91 Aug 04 '17 at 09:03
  • 1
    There are `sizeof unary-expression` and `sizeof ( type-name )`, read about it here: https://stackoverflow.com/questions/18898736/what-does-sizeof-without-do – Andre Kampling Aug 04 '17 at 09:09