C - Pointer

A pointer is a variable whose value is the address of another variable. Like any variable, you must declare a pointer before storing any variable address. The pointer can be declared using * (asterisk symbol).

Syntax: Pointer declaration

int a=10;
int *p;
p=&a;
& (ampersand sign) - Determines the address of a variable.
* (asterisk sign) - Accesses the value from the assigned address.

Example 1: Program to illustrate the use of address of operator '&'.

void main()
{
    int a=10;
    printf("\nValue in variable is %d", a); //10
    printf("\nAddress of variable is %u",&a);
    getch();
}
Value in variable is 10
Address of variable is 64200

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

Example 2: WAP to illustrate the use of Pointer.

void main()
{
    int a=10, *p;
    clrscr();
    p=&a;

    printf("\nValue of A = %d", a); //10
    printf("\nAddress of A = %u",&a);
    printf("\nValue of p = %u",p);
    printf("\nAddress of P = %u",&p);
    printf("\nPointer of p = %d",*p); //10
    getch();
}

Example 3: Pointer can be use as an arrays.

void main()
{
    int a[10],i,*p;
    clrscr();
    printf("Enter 10 numbers : "); 
    for(i=0;i<=9;i++) 
        scanf("%d",&a[i]);
    p=a;
    printf("\nFirst Value : %d",*p); 
    p=p+2;
    printf("\nAfter adding 2 in p : %d",*p); 
    p--;
    printf("\nAfter subtracting 1 in p : %d",*p); 
    getch();
}
Enter 10 numbers : 10 20 30 40 50 60 70 80 90 100
First Value : 10
After adding 2 in p : 30
After subtracting 1 in p : 20

Example 4: Program passing array to function pointer.

void fun(int *p);
void main()
{
    int a[]={1,2,3,4,5};
    clrscr();
    fun(a);
    getch();
}
void fun(int *p)
{
    int i;
    for(i=1;i<=4;i++)
    {
        printf("%d",p[i]);
    }
}
1 2 3 4 5

Example 5: Program to use pointer to access string character-wise.

void main()
{
    char name[]="C-Language";
    char *ptr;
    clrscr();
    while(*ptr!='\0')
    {
        printf("%c",*ptr);
        ptr++;
    }
    getch();
}

Advantages of pointer

  1. Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.
  2. We can return multiple values from function using pointer.
  3. We can dynamically allocate memory using malloc() and calloc() functions where pointer is used.