Beautiful Pointers

Gautam Sawhney
2 min readMay 8, 2020

--

Basics

Pointers are an amazing. C allows the programmer to reference the location of objects and the contents of those location using pointers. A pointer is like any other data type in C. The value of a pointer is a memory location, similar to how the value of an integer is a number. Let's see an example

More details

Consider pntr_money is a pointer to an integer as shown above. Then pntr_money + 1 is a pointer to an integer immediately following the integer *pntr_money in memory, and pntr_money - 1 is the pointer to an integer immediately preceding *pntr_money.

Let us consider a machine which uses byte addressing, an integer requires 4 bytes and the value of pntr_money is 100(that is, pntr_money points to the integer *pntr_money at location 100).

Another thing to remember is the difference between *pntr_money + 1 and *(pntr_money + 1)

Pointers play a prominent rule in passing parameters to functions. Most parameters passed to a function are by value but if we wish to modify the value of the passed parameter we must pass the address of the parameter which is what pointers help with.

Here is an example to understand better -

  • Line 2 prints 5.
  • Line 3 invokes funct and the value passed is the pointer value &x.This is the address of x.
  • The parameter of funct is py of type int *.
  • Line 7 increments the integer at location py, however the value of py which is &x remains the same. Thus py points to the integer x so that when *py is incremented, x is incremented.
  • Line 8 prints 6.
  • Line 4 also prints 6.

Hence, Pointers are the mechanism used in C to allow a called function to modify variables in a calling function.

--

--