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;
?
Printable View
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.Quote:
Originally Posted by Coder87C
Mezzano
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
Works like a charmed ANgel
If you're looking for all-out speed, then unroll the loop (some compilers will do this for you)
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.Code:Xarray[0] = Yarray[0];
Xarray[1] = Yarray[1];
Xarray[2] = Yarray[2];
Xarray[3] = Yarray[3];
Something like this can be amusing.
[edit]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:struct block
{
unsigned char array[4];
};
*(struct block *)Xarray = *(struct block *)Yarray;
Code:mov eax,dword ptr [_Yarray]
mov dword ptr [_Xarray],eax
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. :)