1

After I found this very helpful Q/A: How to initialize all members of an array to the same value?, I came to wonder, if there is an equivalent for my constant problem of how to exchange data between arrays in C.

These are some of the cases which interests me the most:

  1. same type to same type, with same size (e.g char to char)
  2. one type to another, with same size (e.g. const char to unit8)
  3. smaller one into a bigger one (e.g test[7] to test[70])

My methods for those above would be like this - e.g.:

  1. array1 = array2
  2. memcpy(&array2,array1,sizeof(array1))
  3. eighter memcpy too, or a for loop through the elements

I hope someone here can provide, or knows where to find, a fine distilled example-collection of different array exchange routines. It's not, that I cannot make it work my self, it's just, that there is this constant insecurity, if the solution is solid.

Oh, and I really hate those for-loops, assign each element individually. For me, the only reason to use them is when there is some additional handling necessary before the exhange is performed - e.g. incrementing the transferred value first, or something like that.

In case this does not sit well with Q/A-Style, I would be happy, if someone could confirm or improve my attempt for example no.2:

#define SIZEOF_ARRAY = 16;

uint8 array2[SIZEOF_ARRAY+1];
const char array1[SIZEOF_ARRAY+1] = {"test"};

memcpy(&array2,array1,sizeof(array1))
Community
  • 1
  • 1
Jook
  • 4,564
  • 3
  • 26
  • 53
  • Would it be possible to use setup array2 to array1 values though pointers instead of memcpy? My guess was not, because array1 is const. Is that right? – Jook Nov 22 '12 at 15:14

1 Answers1

4

First, your case 1 doesn't make sense, you can't copy to a const array. It's constant.

Then, two nitpicks with your code for the 2nd case:

  1. Array names decay to pointers to the first element in cases like that, so the & is not needed.
  2. sizeof is not a function, so the parenthesis are not needed.

Thus:

memcpy(array2, array1, sizeof array2);

Note that it's a bit dangerous to do this, you must be sure that the sizes really match.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • thanks for the hint with `const`, corrected it. Your reduced form is quite nice, and in my case, I am sure about the size, BUT shouldn't such code always be secured against bad usage? Would you yourself use another way to achieve the same result? – Jook Nov 22 '12 at 15:03