My char pointer points to invalid value after being cast from int*

前端 未结 7 671
余生分开走
余生分开走 2021-02-03 17:19

I am learning C programming language, I have just started learning arrays with pointers. I have problem in this question, I hope the that output must be

7条回答
  •  礼貌的吻别
    2021-02-03 17:55

    On a 32 bit platform, int is four times the size of char. When you add 4 to ptr, you add 4 times the size of what ptr points to to ptr (which itself is a memory location). That happens to be the address of the second element in the int array.

    On a 64 bit platform, int is eight times the size of char; and your output would be very different.

    To cut a long story short, your code is not portable, (also see Joachim Pileborg's answer re endianness) but amusing to unpick.

提交回复
热议问题