Tips on Pointers and Arrays in C

*p++ vs. (*p)++ 

*p++ means *(p++)
  • ++ binds to p, not to *p
  • ++ will increment "p," not "*p," which is the thing that "p" points to
The value of the expression *p++ is the value that p pointed to before being incremented (*p)

Two useful charts










Pointer arithmetic notes

(~pointer~) += (~number~); means (~pointer~) += ~number~) * sizeof((~type~));

  • Pointer arithmetic addition adds multiples of the type size to the memory address
    • Ex. If p is a pointer to an integer, then p += 1 means p += 1 * sizeof(int) 
  • (~pointer name~) + 1 points to the next object in memory (returns a pointer to the next element) 
  • (~pointer name~) + i points to the i-th object beyond (~pointer name~) in memory 
  • (~pointer name~) += i increments (~pointer name~) to point to i elements beyond itself 


Types of valid pointer arithmetic

  • Adding an integer to a pointer
  • Subtracting 2 pointers (in the same array)
  • Comparing pointers (via < <= == != > >=)
  • Comparing pointer to NULL (which indicates that the pointer points to nothing)

Types of illegal pointer arithmetic

  • Adding 2 pointers
  • Multiplying 2 pointers
  • Subtracting a pointer from an integer

Comments

Popular posts from this blog

AI Search Problems Overview

Standard/Planning Search Problems