Introduction

Pointers are a part of the C language and make the C language more powerful. The following arre some features ot them:

  • A pointer mainly represents a data structure.
  • It changes values of an actual argument passed to the function (“call by reference”).
  • It is also for working with memory allocation dynamically.
  • It is efficiently used with integer arrays and character arrays.
  • A pointer always stores a memory address, not data values.
  • A pointer holds the value aa an address.

Declaration

A pointer variable must be declared before use. The syntax for a pointer declaration is as follows.

    Int *a;
    Double *b;

Now a is a “pointer to an integer”and b is a “pointer to a double”.

The prefix * defines the variable as a pointer.

Example

  1. Int *a;
  2. Int b;
  3. a=&b;
Here a contains the memory address of the variable b.

Arithmetic operation are limited to the following for pointers:
  1. Integers and pointers can be added and subtracted.
  2. Incremented and decremented
  3. In addition, pointers can be assigned to each other

Example

  1. Int *a,*b;
  2. a=a+5;
  3. b=a;
Call by Reference

Using call by reference means that a parameter is sent to the function in the form of an address location.
  1. #include<stdio.h>
  2. Void swap(int *p , int *q);
  3. main()
  4. {
  5. Int i=3,j=5;
  6. swap( &I , &j ); //sentind address of I and j variables
  7. printf("After swap, i=%d j=%d\n" ,I ,j );
  8. getch();
  9. return 0;
  10. }
  11. Void swap(int *p, int *q)
  12. {
  13. Int temp;
  14. temp=*p;
  15. *p=*q;
  16. *q=temp;
  17. }
Output

    After swap, I=5 j=3

Pointers and arrays

A pointer always contains the base address of the memory location that makes up an entire array.

Declaration

    Scanf(“%s” ,name);

Example

  1. Int a[5];
  2. a[5]=10;
  3. *(a+5)=56;

All of those are the same thing.

Examples

    1. Int a[100] , I , *p , sum=0;
    2. for (i=0 ; i<100 ;++I )
    3. Sum += a[i];
    1. int a[100] , I , *p , sum=0;
    2. for (i=0 ; i<100 ; ++I )
    3. Sum += *( a + I );
    1. int a[100] , I , *p , sum=0;
    2. for ( p=a ; p<&a[100] ; ++p )
    3. sum += *p;
    The following shows an array as function arguments:
    1. double sum(double *dp , int n )
    2. {
    3. Int I ;
    4. Double res=0.0 ;
    5. for ( i=0 ; i<n ; ++I )
    6. res += *( dp + I ) ;
    7. return res;
    8. }

That function needs a starting address in the array and the number of elements to be summed together.

Pointers and Character Strings

  1. #include<stdio.h>
  2. main()
  3. {
  4. Char *cp ;
  5. cp = "Neeraj Kumar";
  6. printf("%c\n" , *cp );
  7. printf("%c\n" , *( cp + 7 ));
  8. return 0;
  9. }
Output

    N
    K

We can use pointers to work with character strings. The value of the string constant address is the base address of the character array.

Thank you.