Pointers in C Programming

Pointers in C Programming

In this tutorial, you are going to learn about Pointers in C Programming.

Pointers in C Programming

  • Pointers are variables like any other type. However they are also derived type like arrays.
  • Just like other variables, it is mandatory to declare pointers before using them.
  • Pointers can be used to hold “memory address” of other variables of a given type.
  • However just like, each variable has a type, pointers also have type, like:
    • Pointer to an int - It can be used to hold addresses of only and only int variables
    • Pointer to a char - holds addresses of only and only char.

Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer indirectly references a value.  Referencing a value through a pointer is called indirection. A pointer variable must be declared before it can be used.

Concept of Address and Pointers

  • Memory can be conceptualized as a linear set of data locations.
  • Variables reference the contents of locations.
  • Pointers have a value at the address of a given location.
  • Pointer is a value that points to a location in the memory
  • Pointer is associated with a type

Operators used in Pointers

& - "address operator" which gives or produces the memory address of a data variable.

* - "dereferencing operator" which provides the contents in the memory location specified by a pointer.

Pointer Variable Definition

Basic syntax: Type *Name

Examples:

int *P;    /* P is var that can point to an int var */
float *Q;  /* Q is a float pointer */
char *R;   /* R is a char pointer */

Complex example:

int *AP[5];   /* AP is an array of 5 pointers to ints */

Examples of pointer declarations:

int  *a;
float *b;
char *c;

The asterisk, when used as above in the declaration, tells the compiler that the variable is to be a pointer, and the type of data that the pointer points to.

Pointer Initialization and Dereferencing Pointer

  • You need to set proper values (address) to pointers just like you set values for variables, before you can use them.
  • Initialize them at the time of declaration with address of a known variable, example

Method 1: If not initialized, it can later be assigned an address of any variable of the same type, before using it

int *j;
j = &i;                /* assign address

Method 2:

int *j = &i;            /* initialized to address of i.

Note: i should only be of type int and should already be defined or declared

Here ‘&’ is acting as “address of” operator.


This post on Pointers in C Programming is written by Ritika Nagar (BCA, Sharda University). If you like TheCode11, then do follow us on Facebook, Twitter and Instagram.

Previous Post Next Post

Contact Form