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
  • 119,891
  • 44
  • 235
  • 294
Gopi
  • 19,784
  • 4
  • 24
  • 36

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
  • 27,046
  • 9
  • 53
  • 90