Jump to content
  • Advertisement
Sign in to follow this  
MARS_999

Memory copies

This topic is 4410 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I need to copy memory in block segments. e.g.
unsigned char *temp1 = new unsigned char[100];
unsigned char *temp2 = new unsigned char[100];
unsigned char *temp3 = new unsigned char[100];
unsigned char *temp4 = new unsigned char[100];

unsigned char *dest = new unsigned char[400];

//how to memcpy temp1-temp4 so 1,2,3,4 is in numerical order in the dest array?



If I use memcpy() I am assuming I will have to give the address where the first one leaves off and so on... Thanks

Share this post


Link to post
Share on other sites
Advertisement

unsigned char *tmp = dest;
unsigned int stride = sizeof(unsigned char) * 100;

memcpy( tmp, temp1, stride );
tmp += stride;

memcpy( tmp, temp2, stride );
tmp += stride;

memcpy( tmp, temp3, stride );
tmp += stride;

memcpy( tmp, temp4, stride );
tmp += stride;



-me

Share this post


Link to post
Share on other sites
0) Your assumption was correct, and the application is quite trivial, as shown.

1) Any particular reason you're dynamically allocating the memory when you apparently know the size ahead of time?

2) You're not by any chance trying to use char buffers to represent strings, are you? x.x (And even if not, why not use std::vector?)

3) sizeof(unsigned char) == 1 *by definition*.

4) If the stride is constant, we can simplify the logic a fair bit. More so if the original arrays were in an array of their own ;)

4) Don't use memcpy() in C++; use std::copy from <algorithm> :


#include <algorithm>
using std::copy;

copy(temp1, temp1 + stride, dest);
copy(temp2, temp2 + stride, dest + stride);
copy(temp3, temp3 + stride, dest + 2*stride);
copy(temp4, temp4 + stride, dest + 3*stride);

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!