Hi!
I was studying typecasting with pointers when I got stuck on the following exercise:
Code:
#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_pointer = (char*) int_array;
int_pointer = (int*) char_array;
for(i = 0; i < 5; i++) {
printf("[integer pointer] points to %p, which contains the char '%c'\n", int_pointer, *int_pointer);
int_pointer = (int*)((char*) int_pointer+1;
}
}
My question is the following and concerns about the instruction in bold:
- Why do I have to typecast back the pointer? I know what happens if I don't typecast the pointer in order to see good results, but if I run the program without putting that (int*) before the ((char*) int_pointer+1) it works fine, with just a warning from the compiler.
Actually I don't get what happens in memory in order to be necessary to typecast it back.
Thanks in advance!