Andrew Cheong
Andrew Cheong

Reputation: 30273

Is it possible to cast an array of one type to an array of another type whose size is different?

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.

Upvotes: 3

Views: 5871

Answers (3)

ZivS
ZivS

Reputation: 2124

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];

Upvotes: 6

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29022

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.

Upvotes: 1

user2100815
user2100815

Reputation:

 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.

Upvotes: 0

Related Questions