Search code examples
cpointerspointer-arithmetic

What is `*((char*)ptr+4))` doing?


#include<stdio.h>
main()
{
  int a[]={0,2,4,6,8};
  int *ptr;
  ptr=a;
  printf("%d", *((char*)ptr+4));
}

*((char*)ptr+4)) What is the purpose of this?


Solution

  • It's casting the pointer to be viewed as a pointer to char, then adding 4 to look at something 4 char's later in memory, and finally dereferencing the result. In a typical case where int occupies 4 bytes, it'll look at the first byte of the second int in the array. That char will be promoted to an int, passed to printf, and printed out.