Reputation: 553
I want to assign one char array to another, but the following does not work.
unsigned char myval1[6] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
unsigned char myval2[6];
myval2 = &myval1[0];
Upvotes: 0
Views: 308
Reputation: 10126
In C
you an not assign the array. You should use memcpy()
function to copy array.
memcpy(myval2, myval1, sizeof(myval2));
Upvotes: 1
Reputation: 37
try this
unsigned int myval1[6] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
unsigned int myval2[6];
unsigned int* add = &myval1[0];
cout << *add << endl;
Upvotes: 0
Reputation: 141544
A good idiom for this is:
memcpy(&myval2, &myval1, sizeof myval2);
By pairing &x
and sizeof x
you ensure that you always copy the right number of bytes, even if you make a mistake elsewhere with variable names.
The version suggested in the other posts works anyway because myval2
is an array, so (void *)myval2 == (void *)&myval2
.
Upvotes: 0
Reputation: 399743
No, you cannot assign arrays in C.
You must manually copy each array element. The standard library function to do this is memcpy()
:
memcpy(myval2, myval1, sizeof myval2);
The final argument is the number of bytes to copy, and using sizeof
is very much recommended. Note that if myval1
is smaller than myval2
, the above will be undefined behavior since it will read beyond the bounds of myval1
. You must be careful.
Upvotes: 0
Reputation: 217085
C-Array are not copy-assignable.
You have to do the copy yourself (using std::copy
(C++) or memcpy
(C)).
In C++11, you may use std::array
instead.
Upvotes: 2
Reputation: 31290
This is one thing you cannot do with an assignment. One possibility is
memcpy( myval2, myval1, sizeof(myval2) );
Upvotes: 1
Reputation: 1443
You might try something like this..
unsigned char myval1[6] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
unsigned char *myval2;
myval2 = &myval1[0];
Upvotes: 0