[Solved] Converting/typecasting Int pointer to char pointer, but getting ascii characters?


Yes, when you say

point3 = (char*)point

You are converting the integer pointer point to a character pointer point3. point is designed for pointing at whole integers (which of course are multibyte quantities), while point3 can point at individual bytes.

So now point3 points at the individual bytes that point points to, or in other words, the bytes making up the integer f.

But the important point is that the bytes themselves are not changed in any way. By using different kinds of pointers, we can look at the bytes differently, but again, the bytes do not change.

If we say

printf("%d\n", *point);

we take the integer pointer point, fetch the int it points to, and print it. So of course we see “1025“.

If we say

printf("%02x %02x\n", *point3, *(point3 + 1));

we’re using point3 to fetch and print two individual bytes. We might see something like “01 04“. Now, what does that mean?
Well, the number 1025 in hexadecimal (base 16) is 0x401, so we have picked out the two bytes 0x01 and 0x04 which make it up.

(You might wonder why the two bytes look like they’re in the “wrong order”, and this is because of the common “little endian” representation, which is a story for another day. But if you were using a “big endian” machine, with 32-bit ints, you would have seen “00 00“, and you would have been even more confused.)

So why did you get a smiley face and a diamond? I’m not sure, but those are probably the characters with values 1 and 4 on your machine. You were probably trying to print them as characters, not as hexadecimal values like I did.

Finally, you might have thought that by “converting an int pointer to a char pointer” you could somehow convert an integer to a string. But, no, you were not doing anything like that.

Yes, in C, a character pointer (char *) is often used to refer to a string. But this does not mean that by converting something to a char *, you are converting it to a string. (Again, all you’re converting is the pointer.)

The bytes which make up the value 1025 are always going to be 0x04 and 0x01. The only way to convert them to a decimal string (in C) is to call printf and use %d, or to call a nonstandard function like itoa(). Or, in C++, you can use <<.

2

solved Converting/typecasting Int pointer to char pointer, but getting ascii characters?