Monday, May 24, 2010

How can I use pointers to transfer the contents of an array to another of the same size and type in C++?

I need to transfer the contents of a 20-item char array of one object to another, and I'd really like to avoid using for loops (I have to do this several thousand times). is there a way to set a pointer to the first array, and transfer its contents to the second?





Thanks!

How can I use pointers to transfer the contents of an array to another of the same size and type in C++?
With a little work you can reduce the number of steps.





You can cast a pointer to long int to point to your array and move 8 bytes at a time, *only if* you assure that each of your arrays is 8-byte aligned.





The best way to do this is something like the following:





long fakeArray[3];


char *charArray = (char *)fakeArray;





then to copy do something like


long *longPtr = fakeArray, *longPtr2 = fakeArray2;


*longPtr++ = *longPtr2++;


*longPtr++ = *longPtr2++;


*longPtr++ = *longPtr2++;





Maybe even make this a macro:





#define COPY(AAA, BBB) {long *longPtr = (long *) %26amp;(AAA), *longPtr2 = (long *) %26amp;(BBB);\


*longPtr++ = *longPtr2++;\


*longPtr++ = *longPtr2++;\


*longPtr++ = *longPtr2++;\


}





Notice if you do this each of your arrays will need 24 bytes instead of 20, so if you really have a lot of them it will make your memory image larger.





It is often said that premature optimization is a real enemy to good code. Computers are really fast, my guess is that copying short arrays is not going to slow you down very much. Why don't you write the program normally first and then run a profiler to see if this is a problem or not?
Reply:I don't know. I know when programming for Palm, there is an api call named MemMove which will do this, but I don't know for windows.





Maybe you should write that segment in assembly, that would make it quick, but not so easy :)





Hope that helps!
Reply:sorry, u must use a loop to increment the pointer's position


but i guess u can use something called memcpy "it's C not C++ , but i guess u will find it in C++"


or u can use any function that maniuplate strings in C++ like strcat or strcpy and this stuff


sorry if i didn't give u a big help but im really not good in C++, u should move to C# coz it's much better


No comments:

Post a Comment