+ 3
Please, Explain ?
#include <stdio.h> int main() { int a = 320; char *ptr = (char*)&a; printf("%d",*ptr); return 0; } // Output : 64 // How?
5 Answers
+ 15
One char is 1 byte = 2^8 = 256 unique values from 0 to 255. 320 is too big for a char. The char willl overflow and just start counting from 0 if the integer gets larger than 255:
int | corresponding char
----------------------------------------------------
254 | 254
255 | 255
256 | 0
257 | 1
258 | 2
...
319 | 63
320 | 64
321 | 65
...
+ 10
Anna As always... brilliant explanation that is clear and concise. đ
Side note: Since I don't look at C or C++ that often, it still trips me up to see pointer casting done this way. đČ
+ 5
David Carroll yep it is also used in Data File Handling in C++ when we write or read something in binary mode...
For.eg.
file_obj.write((char*)&class_or_struct_obj,sizeof(class_or_struct_obj));
+ 3
Anna Thank you i got it...
it is a very great elaboration...
thanks again...
+ 1
Looking at all the comments, you should be careful about one thing, the C standard does not define if char is signed or unsigned. In this case, it is unsigned but more often that not it is not the case and then the range of acceptable values is -128 .. 127