KEY POINTS TO REMEMBER ABOUT POINTERS IN C:

EXAMPLE PROGRAM FOR POINTERS IN C:

#include <stdio.h>

int main()

{

   int *ptr, q;

   q = 50;

   /* address of q is assigned to ptr */

   ptr = &q;

   /* display q's value using ptr variable */

   printf("%d", *ptr);

   return 0;

}

/*C program to read array elements and print with addresses.*/

#include <stdio.h>

 int main()

{

    int arr[10];        //declare integer array

    int *pa;            //declare an integer pointer

    int  i;

     

    pa=&arr[0];         //assign base address of array

     

    printf("Enter array elements:\n");

    for(i=0;i < 10; i++){

        printf("Enter element %02d: ",i+1);

        scanf("%d",pa+i);   //reading through pointer

    }

     

    printf("\nEntered array elements are:");

    printf("\nAddress\t\tValue\n");

    for(i=0;i<10;i++){

        printf("%08X\t%03d\n",(pa+i),*(pa+i));

    }  

         return 0;

}

Enter array elements:

    Enter element 01: 11

    Enter element 02: 23

    Enter element 03: 444

    Enter element 04: 4

    Enter element 05: 5

    Enter element 06: 6

    Enter element 07: 77

    Enter element 08: 89

    Enter element 09: 67

    Enter element 10: 12

    Entered array elements are:

    Address                        Value

    E73BF180        011

    E73BF184        023

    E73BF188        444

    E73BF18C        004

    E73BF190        005

    E73BF194        006

    E73BF198        077

    E73BF19C        089

    E73BF1A0        067

    E73BF1A4        012

/*C program to read and print student details using structure pointer, demonstrate example of structure with pointer.*/

#include <stdio.h>

 

struct student{

    char    name[30];

    int     roll;

    float   perc;

};

int main()

{

    struct student  std;        //structure variable

    struct student  *ptr;       //pointer to student structure

     

    ptr= &std;                  //assigning value of structure variable

     

    printf("Enter details of student: ");

    printf("\nName ?:");        gets(ptr->name);

    printf("Roll No ?:");       scanf("%d",&ptr->roll);

    printf("Percentage ?:");    scanf("%f",&ptr->perc);

     

    printf("\nEntered details: ");

    printf("\nName:%s \nRollNo: %d \nPercentage: %.02f\n",ptr->name,ptr->roll,ptr->perc);

    return 0;

}

/*C program to print size of different types of pointer variables.*/

#include <stdio.h>

 

int main()

{

    printf("\nsize of char pointer: %d"     ,sizeof(char*));

    printf("\nsize of int pointer: %d"      ,sizeof(int*));

    printf("\nsize of float pointer: %d"    ,sizeof(float*));

    printf("\nsize of long int pointer: %d" ,sizeof(long int*));

    printf("\nsize of double pointer: %d\n" ,sizeof(double*));

    return 0;

}

~~~~ Output depends on the system architecture,

~~~~ but each type of pointer will take same memory space ~~~

/*C program to demonstrate example of DOUBLE POINTER (pointer to pointer).*/

#include <stdio.h>

 int main()

{

    int a;          //integer variable

    int *p1;            //pointer to an integer

    int **p2;           //pointer to an integer pointer

     

    p1=&a;          //assign address of a

    p2=&p1;         //assign address of p1

     

    a=100;          //assign 100 to a

     

    //access the value of a using p1 and p2

    printf("\nValue of a (using p1): %d",*p1);

    printf("\nValue of a (using p2): %d",**p2);

     

    //change the value of a using p1

    *p1=200;

    printf("\nValue of a: %d",*p1);

    //change the value of a using p2

    **p2=200;

    printf("\nValue of a: %d",**p2);

     

    return 0;

}

OUTPUT

Value of a (using p1): 100

    Value of a (using p2): 100

    Value of a: 200

    Value of a: 200

/*C program to demonstrate example of array of pointers.*/

#include <stdio.h>

 

int main()

{

    /*declare same type of variables*/

    int a,b,c;

     

    /*we can create an integer pointer array to

  store the address of these integer variables*/

    int *ptr[3];

     

    /*assign the address of all integer variables to ptr*/

    ptr[0]= &a;

    ptr[1]= &b;

    ptr[2]= &c;

     

    /*assign the values to a,b,c*/

    a=100;

    b=200;

    c=300;

     

    /*print values using pointer variable*/

    printf("value of a: %d, b: %d, c: %d\n",*ptr[0],*ptr[1],*ptr[2]);

 

    /*add 10 to all values using pointer*/

    *ptr[0] +=10;

    *ptr[1] +=10;

    *ptr[2] +=10;

    printf("After adding 10\nvalue of a: %d, b: %d, c: %d\n",*ptr[0],*ptr[1],*ptr[2]);

 

    return 0;

}

value of a: 100, b: 200, c: 300

After adding 10

value of a: 110, b: 210, c: 310

   

/*C program to change the value of constant integer using pointers.*/

#include <stdio.h>

int main()

{  

    const int a=10;     //declare and assign constant integer

    int *p;             //declare integer pointer

    p=&a;               //assign address into pointer p

     

    printf("Before changing - value of a: %d",a);

     

    //assign value using pointer

    *p=20;

     

    printf("\nAfter  changing - value of a: %d",a);

    printf("\nWauuuu... value has changed.");

     

    return 0;

}

Before changing - value of a: 10

    After  changing - value of a: 20

    Wauuuu... value has changed.

C program to print a string using pointer.

/*C program to print a string using pointer.*/

#include <stdio.h>

int main()

{

        char str[100];

        char *ptr;

        

        printf("Enter a string: ");

        gets(str);

        

        //assign address of str to ptr

        ptr=str;

        

        printf("Entered string is: ");

        while(*ptr!='\0')

                printf("%c",*ptr++);

                

        return 0;

}

     Enter a string: Pointer Example string.

    Entered string is: Pointer Example string.

     

/*C program to count vowels and consonants in a string using pointer.*/

#include <stdio.h>

int main()

{

    char str[100];

    char *ptr;

    int  cntV,cntC;

     

    printf("Enter a string: ");

    gets(str);

     

    //assign address of str to ptr

    ptr=str;

     

    cntV=cntC=0;

    while(*ptr!='\0')

    {

        if(*ptr=='A' ||*ptr=='E' ||*ptr=='I' ||*ptr=='O' ||*ptr=='U' ||*ptr=='a' ||*ptr=='e' ||*ptr=='i' ||*ptr=='o' ||*ptr=='u')

            cntV++;

        else

            cntC++;

        //increase the pointer, to point next character

        ptr++;

    }

     

    printf("Total number of VOWELS: %d, CONSONANT: %d\n",cntV,cntC);        

    return 0;

}

VOID POINTERS

We cannt assign a pointer of one type to other type. But, a pointer of any type can be assigned to pointer to void type and a pointer to void type can be assigned to a pointer of any referenced type. We can use Pointer to void to point either an integer or a real number.

 void *p;

Program for Pointer to void:-

#include<stdio.h>

int main(void)

{

void *p;

int i=7;

float f=23.5;

p = &i;

printf(“ i contains %d \n”,*((int *)p));

p=&f;

printf(“f contains %f \n”,*((float *)p);

}

Output: i contains: 7

f contains:23.500000
------------------------------------------------------------------------------------------------------------------------------------------

Memory can be reserved for the variables either during the compilation time or during

execution time. Memory can be allocated for variables using two different techniques:

1. Static allocation

2. Dynamic allocation

1) Static allocation: If the memory is allocated during compilation time itself, the allocated

memory space cannot be expanded to accommodate more data or cannot be reduced to

accommodate less data.

In this technique once the size of the memory is allocated it is fixed. It cannot be altered

even during execution time .This method of allocating memory during compilation time is called

static memory allocation.

2) Dynamic allocation: Dynamic memory allocation is the process of allocating memory during

execution time. This allocation technique uses predefined functions to allocate and release

memory for data during execution time.

Increment  of pointers

#include<stdio.h>

int main(){

int *ptr=(int *)1000;

ptr=ptr+3;

printf("New Value of ptr : %u",ptr);

return 0;

}

Output :

New Value of ptr : 1006

Explanation of Program :

In the above program –

int *ptr=(int *)1000;

this line will store 1000 in the pointer variable considering 1000 is memory location for any of the integer variable.

Formula :

ptr = ptr   + 3 * (sizeof(integer))

    = 1000  + 3 * (2)

    = 1000  + 6

    = 1006

Similarly if we have written above statement like this –

float *ptr=(float *)1000;

then result may be

ptr = ptr   + 3 * (sizeof(float))

    = 1000  + 3 * (4)

    = 1000  + 12

    = 1012

Addition  of Pointers

#include <stdio.h>

int main()

{

    int a, b, *p, *q, sum;

    printf("Enter two integers to add\n");

    scanf("%d%d", &first, &second);

        p = &a;

    q = &b;

        sum = *p + *q;

        printf("Sum of entered numbers = %d\n",sum);

        return 0;

}

Differencing Pointer in C Programming Language :

Differencing Means Subtracting two Pointers.

Subtraction gives the Total number of objects between them .

Subtraction indicates “How apart the two Pointers are ?”

C Program to Compute Difference Between Pointers :

#include<stdio.h>

int main()

{

int num , *ptr1 ,*ptr2 ;

ptr1 = &num ;

ptr2 = ptr1 + 2 ;

printf("%d",ptr2 - ptr1);

return(0);

}

Output :

 2

ptr1 stores the address of Variable num

Value of ptr2 is incremented by 4 bytes

Differencing two Pointers

Important Observations :

Suppose the Address of Variable num = 1000.

Statement

Value of Ptr1

Value of Ptr2

int num , *ptr1 ,*ptr2 ;

Garbage

Garbage

ptr1 = &num ;

1000

Garbage

ptr2 = ptr1 + 2 ;

1000

1004

ptr2 - ptr1

1000

1004

Computation of Ptr2 – Ptr1 :

Remember the following formula while computing the difference between two pointers –

Final Result  = (ptr2 - ptr1) / Size of Data Type

Step 1 : Compute Mathematical Difference (Numerical Difference)

ptr2 - ptr1  = Value of Ptr2 - Value of Ptr1

             = 1004 - 1000

             = 4

Step 2 : Finding Actual Difference (Technical Difference)

Final Result = 4 / Size of Integer

             = 4 / 2

             = 2

Numerically Subtraction ( ptr2-ptr1 ) differs by 4

As both are Integers they are numerically Differed by 4 and Technically by 2 objects

Suppose Both pointers of float the they will be differed numerically by 8 and Technically by 2 objects

Consider the below statement and refer the following table –

int num = ptr2 - ptr1;

and

If Two Pointers are of Following Data Type

Numerical Difference

Technical Difference

Integer

2

1

Float

4

1

Character

1

1

Comparison between two Pointers :

  1. Pointer comparison is Valid only if the two pointers are Pointing to same array
  2. All Relational Operators can be used for comparing pointers of same type
  3. All Equality and Inequality Operators can be used with all Pointer types
  4. Pointers cannot be Divided or Multiplied

Point 1 : Pointer Comparison

#include<stdio.h>

int main()

{

int *ptr1,*ptr2;

ptr1 = (int *)1000;

ptr2 = (int *)2000;

if(ptr2 > ptr1)

   printf("Ptr2 is far from ptr1");

return(0);

}

Pointer Comparison of Different Data Types :

#include<stdio.h>

int main()

{

int *ptr1;

float *ptr2;

ptr1 = (int *)1000;

ptr2 = (float *)2000;

if(ptr2 > ptr1)

   printf("Ptr2 is far from ptr1");

return(0);

}

Explanation :

[box]As we know Pointers can store Address of any data type, address of the data type is “Integer” so we can compare address of any two pointers although they are of different data types.[/box]

Following operations on pointers :

>

Greater Than

<

Less Than

>=

Greater Than And Equal To

<=

Less Than And Equal To

==

Equals

!=

Not Equal

Divide and Multiply Operations :

#include<stdio.h>

int main()

{

int *ptr1,*ptr2;

ptr1 = (int *)1000;

ptr2 = ptr1/4;

return(0);

}

Output :

http://img.c4learn.com/2010/01/pointer-error.jpg

Rules for using Pointer :

  1. Pointer Variable Can be Assigned the address of another Variable

int main() {

     int num = 10;

     int *ptr;

     ptr = &num;

return(0);

}

  1. Pointer Variable Can be Assigned the value of another Pointer Variable

int *sptr,*tptr;

sptr = &num;

tptr = sptr;

  1. Pointer Variable Can be initialized with zero or NULL value.

int *sptr,*tptr;

sptr = 0;

tptr = NULL;

  1. Pointer variable Can be Perform Pre/Post fix Increment/Decrement Operation

int arr[20];

int *ptr;

ptr = &arr;

ptr++;

  1. Integer value can be added or Subtracted from Pointer variable

int arr[20];

int *ptr;

ptr = &arr;

ptr = ptr + 2; //arr[2] will be accessed

  1. When two Pointer points to same array then one Pointer variable can be Subtracted from another
  2. Two Pointers pointing to objects of same data type then they can be compared using the Relational Operator
  3. Value cannot be assigned to arbitrary address

int *ptr;

ptr = 100; //Illegal

Pointer Variable cannot be multiplied by Constant

int *ptr;

ptr = ptr * 6; //Illegal