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:
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.
int *p; //Creates a pointer variable which points to an integer variable.
char *c;//Creates a pointer variable which points to a char variable.
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.
int *p;//declares pointer
p=&a;//stores address of a in p
c=*p;//assigns value at address pointed by p to c
printf("Address of a=%u",p);
printf("Address of a=%u",&a);
printf("Address of c=%u",&c);
printf("Value of c=%d",c);
printf("Value of a=%d",a);
printf("Value of a=%u",*p);
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
The arithmetic operation +, -, ++, — can only be applied on pointers.
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:
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.
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.
int func(int *a,int *b)
Pointers can also be used to return address from a function.
e.g. for function returning address