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

前端 未结 7 678
余生分开走
余生分开走 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 18:14

    What you do is definitely not recommended in production code, but is definitely great for understanding pointers, casts, etc. in the learning process, so for this your example is great. So, why you get 2. It is because your array is an array of ints, which depending on your architecture has different size (in your case, sizeof(int) is 4). You define ptr as being a char pointer, char has size 1 byte. Pointer arithmetics (that's what you do when you write ptr+4) works with size of objects the pointer references, in your case with chars. Thus ptr+4 is 4 bytes away from the beginning of your array, and thus at the 2nd position of your int array. That is it. Try ptr+5, you should get 0.

提交回复
热议问题