Pointers Notes

 Pointer

A pointer is a variable that points to another variable. This means that it holds the memory address of another variable. Put another way, the pointer does not hold a value in the traditional sense; instead, it holds the address of another variable. It points to that other variable by holding its address.  Because a pointer holds an address rather than a value, it has two parts. The pointer itself holds the address. That addresses points to a value. There is the pointer and the value pointed to. 


·       Since ptr is a variable, which contains the address of an integer variable var, it can be declared as:

int *ptr;

where ptr is called a pointer variable.

·       Declaring pointer variable is quite similar to declaring a normal variable but before insert a star “*‟ operator before it.


SYNTAX          data_type * pointer_name;

Where,

1. The asterisk (*): - represents that the variable pointer_name is a pointer variable

2. pointer_name: - represents memory location

3. pointer_name: - represents points to a variable of type data_type.


/*  Program below demonstrates the pointer declaration and initialization. */

# include <stdio.h>

main( )

{

int qty = 5;

int *ptr;     /* declares ptr as a pointer variable that points to an integer                                     variable*/

ptr = &qty;            /* assigning qty’s address to ptr -> Pointer Assignment */

printf ("Address of qty = %u \n", &qty);

printf ("Address of qty = %u \n", ptr);

printf ("Address of ptr = %u \n", &ptr);


printf ("Value of ptr = %d \n", ptr);

printf ("Value of qty = %d \n", qty);

printf ("Value of qty = %d \n", *(&qty));

printf ("Value of qty = %d", *ptr);

}

OUTPUT:            Address of qty = 65524

                        Address of ptr = 65522

                        Value of ptr = 65524

                        Value of qty = 5

                              Value of qty = 5

                        Value of qty = 5

 


Dereferencing of Pointers:

o   It can be used to access or manipulate the data stored at the memory location, which is pointed by the pointer.

o   Any operation applied to the dereferenced pointer will directly affect the value of the variable that it points to.

Let's observe the following steps to dereference a pointer.

    #include <stdio.h> 

    int main() 

    { 

        int x=9; 

        int *ptr; 

        ptr=&x; 

        *ptr=8; 

        printf("value of x is : %d", x); 

        return 0;

 }  


/*  Program for assigning the value to the pointer .*/

  #include <stdio.h> 

 int main() 

 { 

int x=4; 

 int y; 

  int *ptr; 

 ptr=&x;  

y=*ptr; 

*ptr=5; 

printf("The value of x is : %d",x); 

printf("\n The value of y is : %d",y); 

return 0; 

}


POINTER ARITHMETIC


1.     Incrementing or decrementing a pointer (++ or --)
2.     Addition of integer constant to a pointer
3.     Subtraction of integer constant to a pointer
4.     Subtracting two pointers of the same type
5.     Comparison of two pointer variables


1.     Incrementing or decrementing a pointer:

/* Program for increment and decrement operation on pointers. */

void main()

{

   int a, *intPtr;

   float b, *floatPtr, * Ptr;

   intPtr = &a;         // Assume address of a is 1000

   floatPtr = &b;     // Assume address of b is 2000

   Ptr= &b;

  

   intPtr++;            // intPtr = 1000 + 2

   floatPtr++;         // floatPtr = 2000 + 4

   Ptr--;                  // Ptr= 2000-4

   printf("intPtr value : %u\n", intPtr) ;

   printf("floatPtr value : %u\n", floatPtr) ;

   printf("Ptr value : %u\n", Ptr) ;

   getch() ;

}

OUTPUT:              intPtr value: 1002

                                floatPtr value: 2004

                               Ptr value: 1996


2.     Addition of integer constant to a pointer

/*  Program for addition of integer constant operation on pointers. */

void main()

{

   int a, *intPtr ;

   float b, *floatPtr ;

   intPtr = &a ;                       // Asume address of a is 1000

   floatPtr = &b ;                            // Asume address of b is 2000

   intPtr = intPtr + 3 ;                         // intPtr = 1000 + ( 3 * 2 )

   floatPtr = floatPtr + 2 ;                         // floatPtr = 2000 + ( 2 * 4 )

     

   printf("intPtr value : %u\n", intPtr) ;

   printf("floatPtr value : %u\n", floatPtr) ;

    getch() ;

}

OUTPUT:            intPtr value: 1006

                              floatPtr value: 2008


 3.     Subtraction of integer constant to a pointer

/* Program for subtraction of integer constant operation on pointers. */

void main()

{

   int a, *intPtr ;

   float b, *floatPtr ;

   intPtr = &a ;              // Asume address of a is 1000

   floatPtr = &b ;                  // Asume address of b is 2000

   intPtr = intPtr - 3 ;                  // intPtr = 1000 - ( 3 * 2 )

   floatPtr = floatPtr - 2 ;                  // floatPtr = 2000 - ( 2 * 4 )

  

   printf("intPtr value : %u\n", intPtr) ;

   printf("floatPtr value : %u\n", floatPtr) ;

   getch() ;

}

OUTPUT:            intPtr value: 994

                              floatPtr value: 1992


 4.     Subtracting two pointers of the same type

/*  Program for subtraction of two pointers. */

main( )

{

int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;

int *i, *j ;

i = &arr[1] ;

j = &arr[5] ;

printf ( "%d %d", j - i, *j - *i ) ;

}

 

5.     Comparison of two pointer variables

/*  Program for comparison of pointers. */

The following program illustrates how the comparison is carried out.

main( )

{

int arr[ ] = { 10, 20, 36, 72, 45, 36 } ;

int *j, *k;

j = &arr [ 4 ] ;

k = (arr + 4);

if (j == k)

printf (“The two pointers point to the same location”);

else

printf (“The two pointers do not point to the same location”);

}



RELATIONSHIP BETWEEN ARRAYS & POINTERS

/* Program that accesses array elements of a one-dimensional array using pointers  */

# include<stdio.h>

main()

{

int arr[ 5 ] = {10, 20, 30, 40, 50};

int i,*p;

*p=&arr;

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

  {

 printf ("%d", *p[i]);

  }

}

OUTPUT:

                       10            

                       20           

                       30          

                       40          

                       50          


For Two-Dimensional array:

/* Program for Two-dimensional arrays */

main( )

{

int s [2][2] = {7,3,1,4};

int i,*p;

p=&s;

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

{

        printf("%d  \t",*p);

         p++;

}

}

OUTPUT:           7

                                3

                                    1                    

                                        4


/* Program for  usage of pointer to an array */

main( )

{

int s [5][2] = {{1234, 56}, {1212, 33}, {1434, 80}, {1312, 78}};

int (*p) [2];

int i, j, *pint;

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

{

p = &s[i];

pint = p;

printf (“\n”) ;

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

printf (“%d ", *(pint + j));

}

}

OUTPUT:      1234 56

                        1212 33

            1434 80

            1312 78

                  


Array of pointers


/* Program for Array of Pointers */

#include<stdio.h>

int main()

{

  int *arr[5];

  int a = 10, b = 20, c = 30, d = 40, e = 50, i;

  arr[0] = &a;

  arr[1] = &b;

  arr[2] = &c;

  arr[3] = &d;

  arr[4] = &e;

  printf("Address of a = %p\n",arr[0]);

  printf("Address of b = %p\n",arr[1]);

  printf("Address of c = %p\n",arr[2]);

  printf("Address of d = %p\n",arr[3]);

  printf("Address of e = %p\n",arr[4]);

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

  printf("value stored at arr[%d] = %d\n",i,*arr[i]);

 return 0;

}

OUTPUT:            Address of a = 1024

                              Address of b = 2024

                              Address of c = 3024

                              Address of d = 4024

                              Address of e = 5024

                              value stored at arr[0] = 10

                              value stored at arr[1] = 20

                              value stored at arr[2] = 30

                              value stored at arr[3] = 40

                              value stored at arr[4] = 50





POINTER TO POINTER {DOUBLE POINTER}

/*  Program to demonstrate pointer to pointer . */

int main()

{

    int v = 100;

    int *pt1;             // Single pointer for var

    int **pt2;           // double pointer for ptr2

    pt1 = &v;          // storing address of var in ptr2

    pt2 = &pt1;       // Storing address of ptr2 in ptr1

    printf("Value of v = %d\n", var );

    printf("Value of v using single pointer = %d\n", *pt1 );

    printf("Value of v using double pointer = %d\n", **pt2);

    return 0;

OUTPUT:            Value of v = 100

                        Value of v using single pointer = 100

                        Value of v using double pointer = 100



FUNCTIONS AND POINTERS 

/* Program of Function that returns pointer */

#include <stdio.h>

int *getMax(int *, int *);

int main()

{

int x = 100;

int y = 200;

int *max = NULL;

max = getMax(&x, &y);

printf("Max value: %d\n", *max);

return 0;

}

int *getMax(int *m, int *n)

{

      if (*m > *n)

{

                  return m;

      }

else

{

                  return n;

      }

}

OUTPUT:            Max value: 200











Function pointer

/*  Program to invoke function using function pointer. */

#include <stdio.h> 

int main() 

       int a,b; 

       int (*ip)(int,int); 

       int result; 

       printf("Enter the values of a and b : "); 

       scanf("%d %d",&a,&b); 

       ip=add; 

       result=(*ip)(a,b); 

       printf("Value after addition is : %d", result); 

       return 0; 

int add(int a,int b) 

        int c=a+b; 

        return c; 

OUTPUT:            Enter the values of a and b: 5

                          10     Value after addition is :15



DYNAMIC MEMORY MANAGEMENT 

·       Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution.

·      There are two types of memory allocations:

1.     Static Memory Allocation: Static Memory is allocated for declared variables by the compiler. The address can be found using the address of operator and can be assigned to a pointer. The memory is allocated during compile time.

2.     Dynamic Memory Allocation: Memory allocation done at the time of execution (run time) is known as dynamic memory allocation. Functions calloc() and malloc() support allocating dynamic memory. In the Dynamic allocation of memory space is allocated by using these functions when the value is returned by functions and assigned to pointer variables.


Function

Purpose/Discription

malloc()

Allocates the memory of requested size and returns the pointer to the first byte of allocated space.

Calloc()

Allocates the space for elements of an array. Initializes the elements to zero and returns a pointer to the memory.

Realloc()

It is used to modify the size of previously allocated memory space.

Free()

Frees or empties the previously allocated memory space.



/*  Program to understand dynamic allocation of memory using malloc. */

#include<stdio.h> 

#include<stdlib.h> 

int main()

int n,i,*ptr,sum=0;   

printf("Enter number of elements: ");   

scanf("%d",&n);   

ptr=(int*) malloc(n*sizeof(int));        //memory allocated using malloc   

if(ptr==NULL)                        

{   

printf("Sorry! unable to allocate memory");   

exit(0);   

}   

printf("Enter elements of array: ");   

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

{   

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

sum+=*(ptr+i);   

}   

printf("Sum=%d",sum);   

return 0; 

}

 

OUTPUT:

           Enter elements of array: 3

            Enter elements of array: 10

            10

            10

            Sum=30  

/* Program to understand dynamic allocation of memory using calloc(). */

#include<stdio.h>

#include<stdlib.h>

int main()

{

    int *p, i, n;

    printf("Enter the size of the array: ");

    scanf("%d", &n);

    p = (int*)calloc(n, sizeof(int));

    if(p==NULL)

    {

        printf("Memory allocation failed");

        exit(1); // exit the program

    }

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

    {

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

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

    }

    printf("\nPrinting array of %d integers\n\n", n);

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

    {

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

    }

    return 0;

}

OUTPUT:            Enter the size of the array: 5

                        Enter 0 element: 13

                        Enter 1 element: 24

                        Enter 2 element: 45

                        Enter 3 element: 67

                        Enter 4 element: 89

                        Printing array of 5 integers

                        13 24 45 67 89

  

·       Here are important difference between malloc() and calloc():                     [Oct 14, 17]

malloc() Function

calloc() Function

malloc() function will create a single block of memory of size specified by the user.

calloc() function can assign multiple blocks of memory for a variable.

Memory block allocated by malloc function contains garbage value.

The memory block allocated by a calloc function is always initialized to zero.

Number of arguments is 1.

Number of arguments is 2.

malloc is faster than calloc.

calloc is slower than malloc.

Time efficiency is higher than calloc().

Time efficiency is lower than malloc().

It does not perform initializes of memory.

It performs memory initialization.


  

    Resizing Memory Using realloc() Function:

  • Using the realloc() function, you can add more memory size to already allocated memory. It expands the current block while leaving the original content as it is
  • Syntax:

    ptr = realloc(ptr, newSize);

    where ptr is reallocated with new size 'newSize'.



Releasing Memory using free() function:

·       free() is the standard library function used to deallocate memory block that was previously allocated using malloc(), calloc() or realloc(). 

Syntax

void free(void *ptr)


Static Memory Allocation

Dynamic Memory Allocation

In this case, variables get allocated permanently

In this case, variables get allocated only if your program unit gets active

Allocation is done before program execution

Allocation is done during program execution

It uses the data structure called stack for implementing static allocation

It uses the data structure called heap for implementing dynamic allocation

Less efficient

More efficient

There is no memory reusability

There is memory reusability and memory can be freed when not required





. MEMORY LEAK, DANGLING POINTERS

  •       Memory leak occurs when programmers create a memory in heap and forget to delete it.
  •       Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
  •      For the memory leak, some block of memory may have wasted. If the system has enough memory, in that case also this may slow down the performance. 

·       Dangling pointer occurs when the object is deleted or de-allocated from memory without modifying the value of the pointer. In this case, the pointer is pointing to the memory, which is de-allocated.

·       A dangling pointer is a pointer which points to an invalid object.




Comments