3

For example, can I take

int array[12];

and cast it to a char[48] simply by casting the pointer, and given the assumption that int is 4 bytes on my machine? What would be the proper syntax for this, and would it apply generally?

I understand that the size of the new array wouldn't be explicit, i.e. I'd have to do the division myself, again, knowing that on my machine int is 4 bytes.

4
  • I wanted to serialize an integer array to a string (or c-string) without using any library like boost::serialization. It's for a coding exercise. I know I can do it the "naive" way, but wondered about this. Commented Feb 24, 2017 at 21:42
  • Casting pointers may or may not cause any problems. That doesn't indicate anything about whether there will be problems downstream. That depends on how you use the pointers Commented Feb 24, 2017 at 21:46
  • Do you really want to cast int array[12] (48 bytes on your platform) to char array[3] (3 bytes)? Or did you mix up the array bounds? Commented Feb 24, 2017 at 23:16
  • @IInspectable - I just did the math backwards in my example. Correcting, thanks. Commented Feb 25, 2017 at 23:51

3 Answers 3

6

The proper C++ way is with reinterpret_cast :

int array[12];
char* pChar = reinterpret_cast<char*>(array);

You should note that sizeof(array) will be 12*sizeof(int) which is equal to 12 * (sizeof(int) / sizeof(char)), which in most (if not any) machine is larger than sizeof(char[3]) since sizeof(char) is usually a quarter of sizeof(int).

So int array[12]; can be interpeted as char array[12*4];

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

1 Comment

An int is larger than a char on any platform (int is at least 16 bits wide).
1

You can cast most pointer types to most other pointer types using reinterpret_cast.

Usage to : auto ptr = reinterpret_cast<char*>(array);.

Rather than rely on the fact that int is 4 bytes on your system, you can use sizeof(int) as a constant instead. The wording of your question makes it seem like you may be confused about the "size" of the array when cast to char*. int is sizeof(int) times larger than char. If sizeof(int) == 4 then your ints take up 4 * 12 = 48 bytes in your array, not 3.

Comments

0
 int array[12];
 char * p = (char *) array;
 // do what you want with p

Of course, p doesn't have the type char[3], but this probably doesn't matter to you.

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.