Hello, in this code snippet I am not able to understand line 8 and 10. Here at line 8, char* is getting typecasted as int* then again, getting typecasted as char*. Please explain.


int main()
        int arr[3] = {2,3,4};
        char *p;
        p = arr;
        p = (char*)((int*) (p));
        printf("%d \n",*p);
        p = (int*) (p+1);
        printf("%d \n",*p);

Edited by ram619

5 Years
Discussion Span
Last Post by Razahcy

line 8 is nonsense -- no one in his/her right mind would do such a thing. Useless statement.

line 7 might be a problem without typecase.
p = (char*)arr;

line 9 will NOT print the value of arr[0] as you might expect. p is a char pointer, so *p will return only the first byte of an integer.

Edited by Ancient Dragon


That line makes no sense, that's why you don't understand it. As you said, it's casting to int* and then back to char*. It could just as well be written p = p; (or just left out altogether because obviously that's a noop).

Line 7 should be p = (char*) arr;. You need a cast there because only void pointers can be implicitly converted to other pointer types - other pointers or arrays can't (though some (most?) compilers allow it with a warning).

The cast on line 10 doesn't make much sense either. Since p has type char*, this line relies on the int pointer being implicitly converted back to char*, which, as I said regarding line 7, is illegal. And if it was illegal it would be the same kind of pointless to-int*-and-back casting we see on line 8. I.e. it calculates p+1 (using the type char*) and then casts that to int* and then right back to char*. So line 10 is the same as p = p + 1; (except the latter does not rely on an illegal implicit cast).

PS: Your main function is missing a return statement.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.