Jook
Jook

Reputation: 4682

What is the most bulletproof and elegant way, to copy an array to another in different scenarios?

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))

Upvotes: 1

Views: 67

Answers (1)

unwind
unwind

Reputation: 399871

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.

Upvotes: 4

Related Questions