I have found the following code in my lecture book, it works as intended, there is no error, i am just trying to understand it. In the code, we create a char array and an int_pointer. We are able to traverse the char array with the int pointer by typecasting it to a char pointer, such that everytime it gets incremented we move exactly 1 byte forward, instead of 4.
Now my question is why we typecast 2 times. In line 13 (where the comment is) there is the "inner" typecast of (char *) and additionally the "outer" typecast (int *). I understand why the inner typecast is necessary, but why do we need the outer one? I have removed it and yet everything stays the same.
What amazes me even more is that by typecasting it back into an int pointer, the expected length of the referenced data becomes 4 again and yet, when it gets dereferenced it prints out char after char, which indicates that only 1 byte is actually read out, even though we use a pointer that is of type int, which usually reads 4 bytes from where the pointer points to. How can that be?
#include <stdio.h>
int main(){
int i;
char char_array[5] = {'a','b','c','d','e'};
int int_array[5] = {1,2,3,4,5};
char *char_pointer;
int *int_pointer;
char_pointer = (char *) int_array; // Typecast into the
int_pointer = (int *) char_array; // pointer's data type
for (int i=0; i < 5;i++){ // Iterate through the char array with the int_pointer
printf("[integer pointer] points to %p, which contains the char '%c'\n",
int_pointer, *int_pointer);
/* Line 13 */ int_pointer = (int *) ((char *) int_pointer + 1);
}
for (int i=0; i < 5;i++){ // Iterate through the int array with the char_pointer
printf("[char pointer] points to %p, which contains the integer '%d'\n",
char_pointer, *char_pointer);
char_pointer = (char *) ((int *) char_pointer + 1);
} }
OUTPUT
[integer pointer] points to 000000000061FE03, which contains the char 'a'
[integer pointer] points to 000000000061FE04, which contains the char 'b'
[integer pointer] points to 000000000061FE05, which contains the char 'c'
[integer pointer] points to 000000000061FE06, which contains the char 'd'
[integer pointer] points to 000000000061FE07, which contains the char 'e'
[char pointer] points to 000000000061FDE0, which contains the integer '1'
[char pointer] points to 000000000061FDE4, which contains the integer '2'
[char pointer] points to 000000000061FDE8, which contains the integer '3'
[char pointer] points to 000000000061FDEC, which contains the integer '4'
[char pointer] points to 000000000061FDF0, which contains the integer '5'