0
About pointer and array
If we create int array and then cast it into char type (any element) then how much space we have as int and char are different..And please help me understand the code I shared. https://code.sololearn.com/cNjLmvzspVtl/?ref=app
2 Respuestas
+ 3
The space you have available is exactly the same. The only thing that changes is that ptr thinks it's pointing to a char array, so the arithmetic is different when accessing it.
You have an int array with 4 elements. Lets say an int is 4 bytes. ( Not always the case ).
So you have a total of bytes * elements = 4 * 4 = 16 bytes to work with.
If you now do something like arr[2] or *(arr+2) = 3 it has to calculate the offset from the start of the array first. Since the array is an int, 4 * 2 = 8 bytes.
So now it knows it has to start writing data at the 8th byte.
Now you make ptr think it's pointing to a char array. So now it does the math differently.
Lets do ptr[2] or *(ptr+2) = 3 this time.
Now to calculate the offset it uses the size of an char instead of an int. The size of a char is 1 byte. So it knows that it has to start writing at an offset of 1 * 2 = 2 bytes.
The result is that it writes somewhere in the middle of the 1st element in the array.
It's probably easier to have a visual view of this.
So here, feel free to experiment/modify/copy the code.
https://code.sololearn.com/cGnmdDd0IjVk/?ref=app
0
thanks a lot Dennis