Search code examples
c++arrays

Array Casting To Other Array


int* array = new int[5];
array[0] = 65;
array[1] = 66;
array[2] = 67;
array[3] = 68;
array[4] = 69;
char *arr = (char*)array;

So in the above code I'm trying to cast the int array to the char array, Does it's make 4 byte in each index in int array become 1 byte/index in the char arr ?

For example :
65 = 00000000 00000000 00000000 01000001
66 = 00000000 00000000 00000000 01000010
67 = 00000000 00000000 00000000 01000011
68 = 00000000 00000000 00000000 01000100
69 = 00000000 00000000 00000000 01000101

My question is : does this will make the arr char can access around 0-19 index ? Because if you count all the byte the total is 20.


Solution

  • Yes, it will be accessible as a 20-byte array on a system with 4-byte ints

    However, there are several potential problems:

    • C++ does not specify how many bytes are in an int. Most hardware you are likely to compile on these days does use 4-bytes but that is not guaranteed. It may be 2 or 8 on some compilers.
    • The order of the bytes within each int depends on the endianness of the architecture that is being used, and may be different on other hardware. Also, since you mention reading from sockets in another question, remember that the endianness of network traffic can be different from that of the local hardware.
    • You need to be careful with strict aliasing, which can produce unexpected behaviour when optimisations are turned on, because although casting to char* is permitted the inverse cast to int* isn't and, in general, such casts are not safe.
    • Calling delete[] on the casted pointer may fail (but probably won't in this case).

    So you need to apply a great deal of caution when using techniques such as this.

    It's also important to understand that what you are doing here is not casting an array, but rather casting a pointer. Neither the array nor arr variables you have declared will have array type. The first is created as a int* pointer that happens to be initialised to point to a block of memory that has space reserved for five integers, and the second is a reinterpretation of that pointer as pointing to a block of characters instead, but using the same piece of memory.