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;
?
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.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];
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
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
Last edited by Dave_Sinkula; 05-20-2005 at 01:58 PM.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
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.
Last edited by DougDbug; 05-20-2005 at 01:58 PM.