Pointers in C/C++

Rahul BhattRahul Bhatt
2 min read

Remove the limitation of only returning one value

Pointers are identical to a variable but stores the address of another variable. The pointer’s data type will be the same as the data type of the variable. The call by reference method arguments to a function copies the address of an argument into the formal parameter. A variable stores the value and pointer stores the address of a variable. You can visually see the difference in the example given below. A compiler must do these three things for a variable:

  • Reserve space in memory to hold the integer value
  • Associate the name i with this memory location.
  • Store the value 3 at this location.

A function is a self-contained block of statements that performs a coherent task of some kind. A function prototype is a declaration of a function that specifies the function’s name and type signature (arity, data types of parameters, and return type), but discards the function body.

Pointers can also be used to return values indirectly. The code below demonstrates the use of pointers in returning multiple variables indirectly. The addresses of two variables are sent to the function and then manipulation of the data is done on those variables and thus are updated without the need of returning any variable.

Pointers can be used to point to an array. An array is a data structure which comprises of homogenous elements having a similar data type. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. The memory address of the first element of an array is called the first address, foundation address, or base address.

The above code suggests when *p displays the first element from the array, *p+2 displays the third element, and so on. Thus you can use a pointer to access an element from the array.

Thank you for reading.

0
Subscribe to my newsletter

Read articles from Rahul Bhatt directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rahul Bhatt
Rahul Bhatt