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
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.