C Pointers

A pointer is a variable that stores the address of another variable.

A pointer can also be used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous memory location. The purpose of pointer is to save memory space and achieve faster execution time.

j is a pointer

j points to i.

The “address of” (&) operator

The address of operator is used to obtain the address of a given variable

If you refer to the diagrams above

&i=> 87994

&j=>87998

Format specifier for printing pointer address is ‘%u’

The “value of address” operator (*)

The value at address or * operator is used to obtain the value present at a given memory address. It is denoted by *

*(&i) = 72

*(&j) = 87994
How to declare a pointer?

A pointer is declared using the following syntax,

int *j;  => declare a variable j of type int-pointer

j=&i     =>store address of i in j

Just like pointer type integer, we also have pointers to char, float, etc.

int *ch_ptr;       -> pointer to integer

char *ch_ptr;      -> pointer to character

float *ch_ptr      -> pointer to float

Although it’s a good practice to use meaningful variable names, we should be very careful while reading & working on programs from fellow programmers.

A Program to demonstrate Pointers:

#include<stdio.h>
int main()
{
int i=8;
int *j;
j=&i;
printf(“Add i=%u\n”,&i);
printf(“Add i=%u\n”,j);
printf(“Add j=%u\n”,&j);
printf(“Value i=%d\n”,i);
printf(“Value i=%d\n”,*(&i));
printf(“Value i=%d\n”,*j);
return 0;
}

Output:

Add i=87994

Add i=87994

Add j=87998

Value i=8

Value i=8

Value i=8

This program sums it all. If you understand it, you have got the idea of pointers.

Pointers to a pointer:

Just like j is pointing to i or storing the address of i, we can have another variable, k which can store the address of j. What will be the type of k?

int **k;

k= &j;

We can even go further one level and create a variable l of type int*** to store the address of k. We mostly use int* and int** sometimes in real-world programs.

Advantage Of Pointers

  • Pointers allow the passing of arrays and strings to functions more efficiently.
  • Pointers make it possible to return more than one value from the function.
  • Pointers reduce the length and complexity of a program.
  • Pointers increase the processing speed.
  • Pointers save the memory.

Usage of pointer

There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance.

Was this article helpful?
YesNo

Leave a Comment

Your email address will not be published. Required fields are marked *