Pointers in C

Written by

Namrata Jangid

Pointers in C

A pointer is nothing but a variable that points to another variable i.e it stores the address of another variable. It stores the direct address of the memory location. A normal variable stores a value whereas a pointer variable stores the address of another variable.

Declaring a pointer

The syntax for declaring a pointer is –

type *variableName;

– type specifies the data type of the pointer. It must be valid data type in C.
– The * is a unary operator. It is used to indicate that the variable is a pointer.
– varibleName is the name of the pointer variable.
Lets look at an example of pointer declaration:

int *numPtr; // Declaring a pointer numPtr of int type

Initializing a pointer

type *variableName1;
datatype variableName2 = value;
variableName1 = &variableName2;

– type specifies the data type of the pointer. It must be valid data type in C.
– The * is a unary operator. It is used to indicate that the variable is a pointer.
– varibleName1 is the name of the pointer variable.
– varibleName2 is the name of the normal variable that stores any given value. We
want varibleName1 to point to variableName2.
– We use & unary operator to have a pointer point to another normal variable.
Let us look at a code snippet to understand how pointer declaration and initialisation works:

int *numPtr; // Declaring a pointer numPtr of int type
int num = 10; // Initialising a normal variable
numPtr = # // Initialising numPtr as a pointer to num

Please keep in mind that the variable that the pointer points to must be of the same data
type as the pointer’s type.
For example, a char type pointer must point to a char type variable, an int type pointer must
be point to an int type variable, and so on.
Some points to remember for pointers in C:
– The size of any pointer is 2 byte, for 16-bit compiler
– The content of a pointer in C is always a hexadecimal number – the address of the
variable it points to
– * indicates that a variable is a pointer
– & is used to store the address of a variable in a pointer
– If a pointer points to NULL, it means that the pointer is not pointing to anything.
When a pointer is declared, it initially stores NULL. After it gets initialized, the
pointer will store the address of whatever variable it points to.
– The type of the variable should match the type of the pointer that points to it.
Why do we need Pointers in C ?

 

Pointers in C