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:

    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.