# Thread: Cant figure it out.

1. ## Cant figure it out.

Is there a fast way to set 2 unsigned char arrays equal to eachother?

Right now im just running a for loop which sets x[i] = y[i] but is there a way to do

unsigned char Xarray[4];
unsigned char Yarray[4];

Xarray = Yarray;

?

2. Originally Posted by Coder87C
Is there a fast way to set 2 unsigned char arrays equal to eachother?

Right now im just running a for loop which sets x[i] = y[i] but is there a way to do

unsigned char Xarray[4];
unsigned char Yarray[4];

Xarray = Yarray;

?
It is more C'ish but you can use memcpy or memset.

Mezzano

3. memcpy(Xarray,YArray,sizeof(YArray));
beware that if Yarray is a pointer and not an array you'll need so specify the size of the contained buffer on memcpy last paramater

4. Works like a charmed ANgel

5. If you're looking for all-out speed, then unroll the loop (some compilers will do this for you)

Code:
```Xarray[0] = Yarray[0];
Xarray[1] = Yarray[1];
Xarray[2] = Yarray[2];
Xarray[3] = Yarray[3];```
The problem with say memcpy() is that it is likely to be a function call, which can get expensive in comparison if you're only copying small blocks of data.

6. Something like this can be amusing.
Code:
```   struct block
{
unsigned char array[4];
};
*(struct block *)Xarray = *(struct block *)Yarray;```
Hmm. For a Win32 console app using BC55, it makes pretty tiny assembly code; copying all 4 characters at once via a 4-byte register:
Code:
```	mov       eax,dword ptr [_Yarray]
mov       dword ptr [_Xarray],eax```

7. It might seem ridiculous for a large array, but your loop idea is fine. The CPU's little brain can only handle one variable (one element of the array) at a time. ...No matter what technique you use, the machine code has to step-thru the array.

EDIT-
Oh, with character arrays (null-terminated C-style strings) you can use the strcpy() or strncpy() functions in the <cstring> header to copy one character array into another. These functions do the looping for you.

Popular pages Recent additions