Home > OS >  how is the pointer arithmetic operator work in C?
how is the pointer arithmetic operator work in C?

Time:10-04

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

CodePudding user response:

-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

  •  Tags:  
  • c
  • Related