Thursday, 7 August 2014

pointers in C language


Pointer is an important notation in c programming. Pointers points the location of memory. In programming when we declare a variable then, for example
int a = 36;
after looking at the declaration we understand that “a” is a location name in memory and 36 is the value that memory hold. But there is one more thing, the memory have its own location number. The location number may be 34456. Computer select that location itself to place value 36. It not constant, computer may set different location in next compilation. The important thing is “a” address to a memory is a number.
Let’s write a program to understand pointer
#include<stdio.h>
void main()
{
    int a=20;
    printf("address of a = %u\n",&a);
    printf("value of a = %d\n",a);
    printf("value of a = %d\n",*(&a));
}
Before we understand the program let’s see the output of above program is
address of a = 2686748
value of a = 20
value of a = 20
in first “printf()” we printing the memory address of variable “a”. “&” use in this statement is “address of” operator in C language. “&a” return the address of variable “a”, in this case which is “2686748”. This value is not constant, it may different for different program. Here we use “%u” to print address which is a format specifier for unsigned integer.
The other pointer operator in c is “*” called value at address.  It’s give the value stored in a particular address. In above program we print “*(&a)” is produce same result as “a”.
Let’s write another program
#include<stdio.h>
void main()
{
    int a=20;
    int *b;
    b=&a;
    printf("Address of a = %u\n",&a);
    printf("Address of a = %u\n",b);
    printf("Address of b = %u\n",&b);
    printf("Value of b = %u\n",b);
    printf("Value of a = %d\n",a);
    printf("Value of a = %d\n",*(&a));
    printf("Value of a = %d\n",*b);
}
In above program we declare “*b”. it means that variable b will contain an address. Then we write “b=&a” then variable “b” hold address of “b”. That’s why when we printing the value of “b” it will print the address of “a”. we can print the value stored in that address by “*b”.
The output of above program is
Address of a = 2686748
Address of a = 2686748
Address of b = 2686744
Value of b = 2686748
Value of a = 20
Value of a = 20
Value of a = 20

0 comments:

Post a Comment