Pointers

Introduction to pointers


Pointers in C language are is nothing but sort of like a variable which works like a locator/indicator to an address values (hence the name pointer).It helps in reducing the code and returning multiple values from a function.

A pointer have two characteristics one is that it can denote the address location of the saved data, for this we use an ampersand sign (&).Let’s see how

#include<stdio.h>
int main()
{
int a=10;
printf("The number %d is saved in the memory location %x",a,&a);//%x is used for address
return 0;
}

Output :

The number 10 is saved in the memory location ce6aa6f4

The other characteristic is a pointer is that it can also point to the saved data itself using a asterisk sign (*) .Let’s see how

[code language=”c”]
#include<stdio.h>
int main()
{
int a=10;
int *p; //declaration of a pointer
p=&a; // address of data in a is saved in p
printf(“The address of the variable is %x\n”,p);
printf(“And the variable is %d”,*p);
return 0;
}
[/code]

Output :

The address of the variable is 1e3bf13c
And the variable is 10

Note : The pointer variable p stores the value of the address of the data (1e3bf13c) and not the data itself (10), but with the use of *p we can print the data the on that address.

Note : A pointer can be of different types to here we have a integer pointer, we can also have a float pointer, character pointer, string pointer and a NULL pointer (coming up next).

Null pointer

A null pointer is simple a pointer which doesn’t point to anything.We might require this at the start of our code where we have no value to assign to the pointer right now.This can be done as follows

int *p=NULL;

Note : In most libraries the value of a pointer after declaration is 0.

Special operations on pointers

C language has a couple of operation that we can perform on pointer these are

Operations and uses
1 Pointer arithmetic – There are four arithmetic operators that can be used in pointers: ++, –, +, –
2 Array of pointers – You can create arrays to hold a number of pointers.
3 Pointer to pointer – C allows you to have pointer on a pointer and so on.
4 Passing pointers to functions in C – Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function.
5 Return pointer from functions in C – C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory as well.

Let’s see an example that uses these application, take time to understand and absorb this code to fully understand pointers.

[code language=”c”]
#include<stdio.h>
int main()
{
int a=10,b=12,*p1=&a,*p2=&b;
printf(“Value of *p1=%d and *p2=%d before swapping”,*p1,*p2);
//now we swap the number using pointers
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
printf(“After swapping *p1=%d and *p2=%d”,*p1,*p2);
return 0;
}
[/code]

Output :

Value of *p1=10 and *p2=12 before swapping
After swapping *p1=12 and *p2=10