Chapter 9

 

Pointers

 

Pointers are special kind of variable that instead of storing value stores address or represents location of another variable.

Pointers have many advantages. Pointers provide a way to return multiple data items from a function via function arguments. Pointers also closely resemble arrays and therefore provide an alternate way to access individual array elements.

 

Whenever we declare a variable, a memory location is reserved for that variable with name of that variable as its identity. It has some value and an address. (Address is how each memory location is accessed)

 

Declaration of pointer:

 

A pointer variable is declared with data type that of the variable it has to point. Suppose if a pointer has to point to a integer variable than it is declared using pointer data type. A pointer declaration is different from other variable as it uses a character '*' in its declaration.

 

data type * pointer name;

Example:

int *ptr;       here ptr is an integer type pointer.

 

Assigning value to pointer

As pointer variable only stores address of another variable, while assigning its value we use address resolution operator "&" in front of the variable the pointer is suppose to point.


will give following output:

25, fff0

here 25 is the value of x and fff0 is the value of ptr, which in turn is the address of x.

Indirection Operator

There is also a way by which we can show the value of the variable the pointer is pointing. To do so we have to use a operator called indirection operator "*".

 

In above example if we write:

printf("%d", *ptr);

the output will be25, which is value of the variable x, pointed by pointer ptr.

So, indirection operator gives the value of the variable it is pointing. Indirection operator can only be used with pointer variables.

 

Pointer increments and scale factor

Lets say p1 is pointer. p1++ will cause the pointer p1 to point to the next value of its type. For example, if p1 is an integer pointer with an initial value, say 2800, then after the operation p1 = p1 +1, the value of p1 will be 2802, and not 2801. This is, when we increment a pointer, its value is increased by the length of the data type that it points to. This length is called the scale factor.

 

Function call by value

When a single value is passed to a function via an actual argument, the value of the actual argument is copied into the function. Therefore, the value of the corresponding formal argument can be altered within the function, but the value of the actual argument within the calling routine will not change. This procedure for passing the value of an argument to a function is known as passing by value.

 

 

Example:

# include <stdio.h>

void modify(int a); /*function prototype*/

main()

    {

    int a=2;

    printf(“\na=%d (from main, before calling the function)”,a );

    modify(a);

    printf(“\n\na=%d (from main, after calling the function)”,a);

    }

void modify(int a)

    {

    a*=3;

    printf(“\n\n a=%d )from the function, after being modified)”, a);

    return 0;

    }

 

After the execution of program

a = 2 (from main, before calling the function)

a = 6 (from the function, after being modified)

a = 2 (from main, after calling the function)

 

Function Call by Reference

 

In the second method (call by reference) the address of actual arguments in the calling function are copied into formal arguments of the called function. This that using the formal arguments in the called function we can make changes in the actual arguments of the calling function. The following program illustrates this fact.

#include <stdio.h>

#include<conio.h>

void interchange(int *a, int *b)

    {

    int temp;

    temp=*a;

    *a=*b;

        *b=temp;

    }

void main()

    {

    int a=5, b=10;

    printf("\nBefore function call a=%d, b=%d", a,b)

    interchange(&a, &b);

    printf("\nAfter function call a=%d b=%d", a, c);

    getch();

    }

Output of the program will be:

Before function call a=5, b=10

After function call a=10, b=5

 

 

// program to illustrate swapping of two variables by pointer and function.

 

#include<stdio.h>

void swap(int *, int*);

 

void main()

{

 

int num1=10,num2=20;

printf(“Before executing swap()\n”);

printf(“The value of num1=%d\n”,num1);

printf(“The value of num2=%d\n”,num2);

 

swap(&num1,&num2);

 

printf(“After executing swap()\n”);

printf(“The value of num1=%d\n”,num1);

printf(“The value of num2=%d\n”,num2);

}

void swap(int *n1, int *n2)

{

int temp;

temp=*n1;

*n1=*n2;

*n2=temp;

}

Output:

Before executing swap()

The value of num1=10

The value of num2=20

After executing swap()

The value of num1=20

The value of num2=10

 

Pointers and Array

When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element (index 0) of the array. . Suppose we declare an array x as follows:

               int x[5] = {1,2,3,4,5};

The five elements will be stored as follows:

The x (name of the array) is defined as a constant pointer pointing to the first element, x[0] and therefore the value of x is 5000, the location where x[0] is stored. That is,

        x= &x[0] = 5000;

If we declare p as an integer pointer, then we can make the pointer p to point to the array x by the following assignment:

        p = x;

This is equivalent to

        p = &x[0];

Now, we can access every value of x using p++ to move from one element to another. Since incrementing an array pointer causes it to point to the next element, we need only to add one to p each time we go through the loop. 

The relationship between p and x is shown below: 

P   =&x [0] (=5000)

P+1 =&x [1] (=5002)

P+2 =&x [2] (=5004)

P+3 =&x [3] (=5006)

P+4 =&x [4] (=5008)

 

 

 

 

 

 

 

 

 


Similary, we also have

*P          =x [0]      =1

*(P+1)      =x [1]      =2

*(P+2)      =x [2]      =3

*(P+3)      =x [3]      =4

*(P+4)      =x [4]      =5

 

 

 

 

 

 

 

  

Example: Program to find sum of all the elements of array using pointer notation.

#include<stdio.h>

#include<conio.h>

void main()

    {

    int a[100], i,n,sum=0;

    int *p;

    ptr=a;

    printf("\nNumber of elements:");

    scanf("%d", &n);

    for(i=0; i<n; i++)

         {

        printf("\nEnter data:");

         scanf("%d", p+i);

         }

    for(i=0; i<n; i++)

         {

         sum=sum+*(p+i);

         }

    printf("\nSum of all the elements of arrays is %d", sum);

    getch();

    }

 

Passing Array to Function

One dimensional array can be passed to function using the analogy just discussed above. As an array can be represented and accessed using one pointer, we can pass the pointer to the function. As this is function call by reference any changes made to the array in the function is also reflected inside the main function.

Example: Using function to take input and display an array.

#include<stdio.h>

#include<conio.h>

void input(int *p, int n)

    {

    int i;

    for(i=0; i<n; i++)

         {

         printf("\nEnter data:");

         scanf("%d", p+i);

         }

    }

 

void display (int *p, int n)

    {

    int i;

    for(i=0; i<n; i++)

         {

         printf("\n %d", *(p+i));

         }

    }

void main()

    {

    int n, a[100];

    int *ptr;

    ptr=a;

    clrscr();

    printf("\nenter number of data:");

    scanf("%d", &n);

    input(ptr,n);

    display(ptr, n);

    }

Pointers and Multi-dimensional Array

As single pointer can be used to access and manipulate all the elements of single dimensional array, it can be used to access all the elements of multi dimensional array. When an multi dimensional array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The contiguous memory location is given in order of elements of each row as shown in figure below. Let us declare and multi dimensional array x[5][5], then


If the base address of this array is 5000, i.e. x[0][0]=5000, then x[0][1]=5002, x[0][2]=5004 and so on.

 

We cannot declare a pointer that will point to an multi dimensional array but we can use name of the array as pointer. Now the relationship between pointer and the array elements can be shown as below:

x            =   &x [0] [0]

(*(x+0) +1)  =   &x [0] [1]

(*(x+0) +2)  =   &x [0] [2]

(*(x+0) +3)  =   &x [0] [3]

(*(x+0) +4)  =   &x [0] [4]

(*(x+1) +0)  =   &x [1] [0]

(*(x+1) +1)  =   &x [1] [1]

(*(x+1) +2)  =   &x [1] [2]

and so on.

 

Using this analogy we can access all the elements of an multi dimensional array.

 

Passing Multi-dimensional array to Function

 

To pass a multidimensional array to function in function prototype we give parameter of the function as multi dimensional array. For example a function taking integer two dimensional array will have parameter defined as:

input(int a[][])

In function call we use name of the array to pass value to this parameter.

 

Example: Program to calculate sum of all the elements of an array using function call.

#include<stdio.h>

#include<conio.h>

void input(int a[3][3])

    {

    int i,j;

    for(i=0; i<3;i++)

         {

         for(j=0; j<3; j++)

             {

             printf("\nenter value:");

             scanf("%d", &a[i][j]);

             }

         }

    }

int calsum(int a[3][3])

    {

    int i, j, sum=0;

    for(i=0; i<3; i++)

         {

         for (j=0; j<3; j++)

             {

             sum=sum+a[i][j];

             }

         }

    return sum;

    }

 

void main()

    {

    int a[3][3],i,j,sum;

    clrscr();

    input(a);

    for(i=0; i<3; i++)

         {

         for(j=0; j<3; j++)

             {

             printf("\t%d", a[i][j]);

             }

         printf("\n");

         }

    sum=calsum(a);

    printf("\nSum of the elements of array:%d", sum);

    getch();

    }

 

 

 

Void pointer

 

Pointer defined to be of a specific data type cannot hold the address of any other type of variable.

e.g. float *float_ptr;  //declare pointer to float

 

An exception to this restriction is a general purpose pointer type called the void pointer. The format for declaring a void pointer is as follows.

 

void *void_ptr; //declare a pointer to void

 

This declaration uses the C reserved word void for specifying the typr of the pointer/ Pointers declared in this manner do not have any type associated with them and can contain the address of any type of variable (int char, float etc).

 

// program to illustrate void pointer

 

#include<stdio.h>

#include<conio.h>

void main()

{

 

int ival=240;

float fval=324.45;

void *ptr;

ptr=&ival;

printf("ival contains %d\n",*((int*)ptr));

ptr=&fval;

printf("fval contains %f\n",*((float*)ptr));

getch();

}

 

Output:

ival contains 240

fval contains 324.5

  Full Width

 

 

 

 

 



Post a Comment

0 Comments