DEV Community

Gautam Sawhney
Gautam Sawhney

Posted on

Beautiful Pointers

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

int money = 10
pntr_money = &money

pntr_money - is an integer pointer which would hold the address of money which is &money.
*pntr_money - points to the value in the variable money which is 10.

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).

pntr_money = 100
pntr_money - 1 = 96
pntr_money + 1 = 104
pntr_money + 2 = 108

*(pntr_money - 1) = Contents of the 4 bytes 96, 97, 98 and 99 interpreted as an integer.
*(pntr_money + 1) = Contents of the 4 bytes 104, 105, 106 and 107.

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

*pntr_money + 1 - This will increase the value in pntr_money by 1
*(pntr_money + 1) - This will point to the value at the address which is (pntr_money + 1)




Example

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 -

Program

  • 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.

Top comments (0)