Pointers

Pointer :

Pointers are the variables which are used to store the address of another variable in memory, or say, points to another variable. Like every other variable, pointer also needs to be declared before use.The syntax for declaring a pointer is as follows:

data_type *pointer_name;

Here, data type defines what type of value the pointer is going to point ,not as usual type of variable. Type of pointer remains same i.e. unsigned integer.

e.g

int *p;  //Creates a pointer variable which points to an integer variable.

char *c;//Creates a pointer variable which points to a char variable.

USING POINTERS:

There are two operators used for pointers,

&(address of) and *(value at the address) of operator.

Both are unary operators & give the address of the variable and * gives the address stored at given address.

e.g

NULL POINTERS:

NULL pointer is a pointer which points to nothing. NULL value is assigned to a pointer when the exact address is not known. Pointer initializes is said to be NULL pointer.

NULL is macro constant defined in header files stdio.h, alloc.h, mem.h, stddef.h and stdlib.h

POINTER ARITHMETIC:

The arithmetic operation +, -, ++, — can only be applied on pointers.

e.g

p++ will increment the value by four. Like if p stores address 100 then p++ will point to next integer location 4 bytes next to location of p(because size of int is 4bytes), initially, i.e. 104. Similarly, if decremented ,i.e. p– will point to 4 bytes previous address i.e. 96

Relational operators such as ,= can also be with pointer to compare the values.

ARRAY OF POINTERS:

An array of pointers can also be declared to store the address of variables. Syntax is:

data_type *arrayname[max];

e.g

char *ptr[5];

declares ptr as an array of 5 character pointers. Thus, each element in ptr, now holds a pointer to an char value.p;

POINTER TO POINTER :

A pointer to a pointer can also be made. It holds the address of the pointer pointing the variable.

A pointer to pointer can be declared with an extra astrik.

e.g

int **p;//declares a pointer to a pointer.

POINTERS & FUNCTIONS:

Pointers can also be passed as an argument to a function. Such method of passing arguments is called Call By Reference. In such method, all the changes to a variable are directly done to the address passed.

e.g.

int func(int *a,int *b)

Pointers can also be used to return address from a function.

e.g. for function returning address

int *func();

Leave a Reply

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