0

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];
1
  • What you are trying to do gives compiler error because, an array variable here myval1,myval2 are always constant type, so you cannot modify base address of an array which you are actually doing in your solution. You can follow any of the answers given below for copying your arrays. Commented Apr 7, 2014 at 9:47

7 Answers 7

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This is one thing you cannot do with an assignment. One possibility is

memcpy( myval2, myval1, sizeof(myval2) );

Comments

1

In C you an not assign the array. You should use memcpy() function to copy array.

memcpy(myval2, myval1, sizeof(myval2));

Comments

0

You might try something like this..

unsigned char myval1[6] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
 unsigned char *myval2;
 myval2 = &myval1[0];

1 Comment

Probably not what OP had in mind. It creates an alias for myval1 and does not copy any values.
0

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.

Comments

0

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.

Comments

0

try this

unsigned int myval1[6] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
unsigned int myval2[6];
unsigned int* add = &myval1[0];

cout << *add << endl;

2 Comments

and how does this copy the values of myval1 to maval2 ?
there is no myval2 here, you need to use variable add, add++ to access next values. Yes variable add address will be pointing to the starting address of myval1 so *add will print 1 ; *add++ = 1 [myval1[1]] ; *add++ = 1 [myval1[2]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.