Typecasting int to char in printf() in C

前端 未结 4 476
南笙
南笙 2020-12-20 00:47
int *int_pointer = malloc(10);

*int_pointer = 53200;

printf(\"The integer at byte #0 is set to: %d \\n\", (char) *int_pointer);

RESULT: -48

4条回答
  •  长情又很酷
    2020-12-20 01:35

    Casting a data type into another data type that isn't wide enough to hold all possible values is undefined behaviour. With undefined behaviour, the compiler is free to do whatever it pleases, so typically it does whatever is the least effort for the implementors, since they are automatically right and you are always wrong.

    Therefore, you don't get to ask "Why did it happen?" - you should be glad you didn't get 52301, or 42, or "Help! I'm trapped in an integer library!" instead.

提交回复
热议问题