-1

is ++ in c pointer is a kind of operator overloading ,which similar to C++? i wonder how this pointer arithmetic work?

#include <stdio.h>
int main(){
  int i[5]={1,2,3,4,5};                 int    *pi=i;
  double f[5]={1.0,2.0,3.0,4.0,5.0};    double *pf=f;

  printf("sizeof int:%lu bytes\tsizeof double:%lu bytes\t\n"
         ,sizeof (int),sizeof (double ));
  printf("i[0]: %d \tMemAddress:%p\t\n",*pi,pi);
  printf("i[1]: %d \tMemAddress:%p\t\n",*++pi,pi);
  printf("f[0]: %f \tMemAddress:%p\t\n",*pf,pf);
  printf("f[1]: %f \tMemAddress:%p\t\n",*++pf,pf);
}


enter image description here

q2333
  • 33
  • 1
  • 6
  • Try reading Chapter 5 of K&R. It should give you most of the answers you are looking for. – cup Oct 03 '22 at 06:55
  • Pointers are just numbers, the `++` operator works the same as it does for any other numeric type (other than it increments by the size of the pointed to type rather than by 1) – Alan Birtles Oct 03 '22 at 06:59
  • 1
    This has absolutely nothing to do with operator overloading and also works the same in C and C++. – Lundin Oct 03 '22 at 07:30
  • https://stackoverflow.com/questions/394767/pointer-arithmetic – mmixLinus Oct 03 '22 at 07:50

1 Answers1

1

++-ing / ---ing a pointer in C adds or subtracts sizeof(the type that pointer points to) to the pointer.

e.g.

Assume that an int takes up 4 bytes in memory, and there's an int pointer named p that points to some memory address, like 0x10000000. p++ will cause p to point to 0x10000004.

ppt from Berkeley CS61C

q2333
  • 33
  • 1
  • 6