Reputation: 30273
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
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
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 int
s take up 4 * 12 = 48
bytes in your array, not 3.
Upvotes: 1
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