Please, Explain ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Please, Explain ?

#include <stdio.h> int main() { int a = 320; char *ptr = (char*)&a; printf("%d",*ptr); return 0; } // Output : 64 // How?

9th May 2019, 7:31 AM
Sp Maurya
Sp Maurya - avatar
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 ...
9th May 2019, 7:49 AM
Anna
Anna - avatar
+ 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. 😲
9th May 2019, 8:22 AM
David Carroll
David Carroll - avatar
+ 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));
9th May 2019, 8:30 AM
Sp Maurya
Sp Maurya - avatar
+ 3
Anna Thank you i got it... it is a very great elaboration... thanks again...
9th May 2019, 8:25 AM
Sp Maurya
Sp Maurya - avatar
+ 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
11th May 2019, 5:17 PM
Paul