Reputation: 4682
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:
My methods for those above would be like this - e.g.:
array1 = array2
memcpy(&array2,array1,sizeof(array1))
memcpy
too, or a for loop through the elementsI 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
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:
&
is not needed.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