3

I want to convert an array of int to an array of char and then back again, for serialization purposes. It does not need to work cross-platform.

I came up with

  //sample int array 
  int arr[] = {1,2,3,4,100};
  char char_arr[sizeof(arr)];
  //int arr to char arr
  memcpy(char_arr, arr, sizeof(arr));

  int newarr[sizeof(char_arr)/sizeof(int)];
  //char arr back to int arr
  memcpy(newarr, char_arr, sizeof(char_arr)/sizeof(int));

This does not seem to work however (newarr contains values different from arr). Any suggestions?

3
  • While you get the number of entries right in newarr the size when you copy to it is still sizeof(char_arr), i.e. do not divide by sizeof(int). Commented Dec 9, 2011 at 11:42
  • You don't need to divide by sizeof(int) in the call to memcpy. Commented Dec 9, 2011 at 11:45
  • Think again whether you really need this. Perhaps a reinterpret_cast<const char *>(arr) will suffice for your application? Commented Dec 9, 2011 at 13:14

2 Answers 2

6

The third argument to memcpy is number of bytes*, not number of elements. So your second memcpy call is incorrect.


* Number of chars, technically.

Sign up to request clarification or add additional context in comments.

Comments

0

memcpy copies memory bytes, not array elements and thus does no array element conversion for you. If you want to convert an array of chars to an array of ints you might try std::copy which copies containers element by element.

int newarr[sizeof(char_arr)/sizeof(char_arr[0])]; 
std::copy(&char_arr[0], &char_arr[sizeof char_arr/sizeof char_arr[0]], newarr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.