0

I see the below code snippet always return 1 instead of 4 Not able to really make out what is wrong

#include <stdio.h>
int main(void) {
   int a[4] = {1,2,3,4};
   int *p = a;

   p++;
   printf("%ld\n",(long int)(p-a));
   return 0;
}
Yu Hao
  • 115,525
  • 42
  • 225
  • 281
Gopi
  • 19,679
  • 4
  • 22
  • 35

1 Answers1

4

This is the basics of pointer arithmetic. When you have:

int a[4] = {0};
int *p = a;

when you do p++ - compiler automatically increases p with four bytes (in case size of integer is four). Same happens with subtraction if you subtract 1 from p compiler will automatically subtract four bytes. But to more precisely answer your question it seems - operator when applied to pointer types divides result on size of element type to which pointer points to.

Giorgi Moniava
  • 23,407
  • 6
  • 45
  • 84