UNIT 3

 


void pointer(general purpose pointer) can be used to store address of any varible.



wild pointers are pointers which are not initialised and store garbage value . to error aa skta hai .












>>

   #include<stdio.h>

       struct Employee

      {

             int Id;

             char Name[25];

             int Age;

             long Salary;

      };

       void Display(struct Employee*);

      int main()

      {

             struct Employee Emp = {2,"ram",28,35000};

              Display(&Emp);

       }

       void Display(struct Employee *E)

      {

                   printf("\n\nEmployee Id : %d",E->Id);

                   printf("\nEmployee Name : %s",E->Name);

                   printf("\nEmployee Age : %d",E->Age);

                   printf("\nEmployee Salary : %ld",E->Salary);

      }


>>

     #include<stdio.h>

       struct Employee

      {

             int Id;

             char Name[25];

             int Age;

             long Salary;

      };

       Employee Input();           //Statement  1

      int main()

      {

             struct Employee Emp;

              Emp = Input();

              printf("\n\nEmployee Id : %d",Emp.Id);

             printf("\nEmployee Name : %s",Emp.Name);

             printf("\nEmployee Age : %d",Emp.Age);

             printf("\nEmployee Salary : %ld",Emp.Salary);

       }

       Employee Input()

      {

             struct Employee E;

                    printf("\nEnter Employee Id : ");

                   scanf("%d",&E.Id);

                    printf("\nEnter Employee Name : ");

                   scanf("%s",&E.Name);

                    printf("\nEnter Employee Age : ");

                   scanf("%d",&E.Age);

                    printf("\nEnter Employee Salary : ");

                   scanf("%ld",&E.Salary);

             return E;            //Statement  2

      }


>>

#include <stdio.h>

//Structure declartion

struct employee {

   char name[40];

   int empid;

   int experience;

}emp;

void displaydetails(struct employee*); //function declaration

int main()

{

struct employee *empptr;  //pointer declaration

empptr = &emp;  //initial

printf("\nEnter the name of the Employee : ");

scanf("%s", empptr->name);

printf("\nEnter the Employee Id : ");

scanf("%d",&empptr->empid);

printf("\nEnter Experience of the Employee : ");

scanf("%d",&empptr->experience);

displaydetails(empptr);

return 0;

}

//Function Definition

void displaydetails(struct employee *empptr)

{

printf("\n---------Details List--------- \n ");

printf("Employee Name : %s",empptr->name);

printf("\nEmployee ID : %d ",empptr->empid);

printf("\nEmployee Experience : %d ",empptr->experience);

}


>>


#include<stdio.h>

struct team {

   char *name;

   int members;

   char captain[20];

}

t1 = {"India",11,"Dhoni"} , *sptr = &t1;

 

int main()

{

 

printf("\nTeam : %s",(*sptr).name);

printf("\nMemebers : %d",sptr->members);

printf("\nCaptain : %s",(*sptr).captain);

 

return 0;

}




>>



>> DMA is used to increase orr decrease size of array or to allocate memory.

  • A Pointer is the only way to access Dynamic Memory Allocation.

>>To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and free() are used. These functions are defined in the <stdlib.h> header file.



>> malloc()  memory allocation


#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));


    // if memory cannot be allocated

   if(ptr == NULL)                    

    {

       printf("Error! memory not allocated.");

       exit(0);

   }


   printf("Enter elements: ");

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

   {

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

       sum += *(ptr + i);

   }


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

 

    


   return 0;

}


>>calloc() -- contagious allocation


#include <stdio.h>

#include <stdlib.h>


int main()

{

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

   printf("Enter number of elements: ");

   scanf("%d", &n);


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

   if(ptr == NULL)

   {

       printf("Error! memory not allocated.");

       exit(0);

   }

else{

   printf("Enter elements: ");

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

   {

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

       sum += *(ptr + i);

   }


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

   return 0;

}



>>difference between calloc and malloc is that the memory that is allocated by calloc is initialized with 0.

and calloc take 2 arguments and malloc take 1.


>>Malloc() and calloc() both functions return void* (a void pointer), to use/capture the returned value in pointer variable we convert it's type.



>>

Example: Program to Represent the reallocation in memory using realloc().

  #include <stdio.h>

#include <stdlib.h>

  

int main()

{

  

    // This pointer will hold the

    // base address of the block created

    int* ptr;

    int n, i;

  

    // Get the number of elements for the array

    n = 5;

    printf("Enter number of elements: %d\n", n);

  

    // Dynamically allocate memory using calloc()

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

  

    // Check if the memory has been successfully

    // allocated by malloc or not

    if (ptr == NULL) {

        printf("Memory not allocated.\n");

        exit(0);

    }

    else {

  

        // Memory has been successfully allocated

        printf("Memory successfully allocated using calloc.\n");

  

        // Get the elements of the array

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

            ptr[i] = i + 1;

        }

  

        // Print the elements of the array

        printf("The elements of the array are: ");

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

            printf("%d, ", ptr[i]);

        }

  

        // Get the new size for the array

        n = 10;

        printf("\n\nEnter the new size of the array: %d\n", n);

  

        // Dynamically re-allocate memory using realloc()

        ptr = realloc(ptr, n * sizeof(int));

  

        // Memory has been successfully allocated

        printf("Memory successfully re-allocated using realloc.\n");

  

        // Get the new elements of the array

        for (i = 5; i < n; ++i) {

            ptr[i] = i + 1;

        }

  

        // Print the elements of the array

        printf("The elements of the array are: ");

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

            printf("%d, ", ptr[i]);

        }

  

    }

  

    return 0;

}


>>

  C free()

free method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

Syntax:

free(ptr);


Example : Program to demonstrate free() in C.

#include <stdio.h>

#include <stdlib.h>

  

int main()

{

  

    // This pointer will hold the

    // base address of the block created

    int *ptr, *ptr1;

    int n, i;

  

    // Get the number of elements for the array

    n = 5;

    printf("Enter number of elements: %d\n", n);

  

    // Dynamically allocate memory using malloc()

    ptr = (int*)malloc(n * sizeof(int));

  

    // Dynamically allocate memory using calloc()

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

  

    // Check if the memory has been successfully

    // allocated by malloc or not

    if (ptr == NULL || ptr1 == NULL) {

        printf("Memory not allocated.\n");

        exit(0);

    }

    else {

  

        // Memory has been successfully allocated

        printf("Memory successfully allocated using malloc.\n");

  

        // Free the memory

        free(ptr);

        printf("Malloc Memory successfully freed.\n");

  

        // Memory has been successfully allocated

        printf("\nMemory successfully allocated using calloc.\n");

  

        // Free the memory

        free(ptr1);

        printf("Calloc Memory successfully freed.\n");

    }

  

    return 0;

}


>> 1d array using pointer


#define FAIL 1

#define TRUE 0

int main(int argc, char*argv[])

{

int *piBuffer = NULL; //pointer to integer

int nBlock = 0; //Variable store number ofblock

int iLoop = 0; //Variable for looping

printf("\nEnter the number of block =");

scanf("%d",&nBlock); //Getinput for number of block

piBuffer = (int *)malloc(nBlock *sizeof(int));

//Check memory validity

if(piBuffer == NULL)

{

return FAIL;

}

//copy iLoop to each block of 1D Array

for (iLoop =0; iLoop < nBlock; iLoop++)

{

piBuffer[iLoop] = iLoop;

}

//Print the copy data

for (iLoop =0; iLoop < nBlock; iLoop++)

{

printf("\npcBuffer[%d] =%d\n", iLoop,piBuffer[iLoop]);

}

// free allocated memory

free(piBuffer);

return TRUE;

}



>> 2d arrray using pointer

Using a single pointer:


int main()

{

int r = 3, c = 4;

int *arr = (int *)malloc(r * c *sizeof(int));

int i, j, count = 0;

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

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

*(arr + i*c + j) = ++count;

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

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

printf("%d ", *(arr + i*c +j));

/* Code for further processing and freethe

dynamically allocated memory */

return 0;

}





Using an array of pointers


int main()

{

int r = 3, c = 4, i, j, count;

int *arr[r];

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

arr[i] = (int *)malloc(c *sizeof(int));

// Note that arr[i][j] is same as*(*(arr+i)+j)

count = 0;

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

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

arr[i][j] = ++count; // Or*(*(arr+i)+j) = ++count

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

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

printf("%d ", arr[i][j]);

/* Code for further processing and freethe

dynamically allocated memory */

return 0;

}



Using pointer to a pointer



int main()

{

int r = 3, c = 4, i, j, count;

int **arr = (int **)malloc(r * sizeof(int*));

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

arr[i] = (int *)malloc(c *sizeof(int));

// Note that arr[i][j] is same as*(*(arr+i)+j)

count = 0;

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

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

arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count

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

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

printf("%d ", arr[i][j]);

/* Code for further processing and freethe

dynamically allocated memory */

return 0;

}



Using double pointer and one malloc call


int main()

{

int r=3, c=4, len=0;

int *ptr, **arr;

int count = 0,i,j;

len = sizeof(int *) * r + sizeof(int) * c* r;

arr = (int **)malloc(len);

// ptr is now pointing to the first elementin of 2D array

ptr = (int *)(arr + r);

// for loop to point rows pointer toappropriate location in 2D array

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

arr[i] = (ptr + c * i);

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

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

arr[i][j] = ++count; // OR *(*(arr+i)+j)= ++count

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

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

printf("%d ", arr[i][j]);

return 0;

}



>>memory allocation to sturcture


#include <stdio.h>

#include <stdlib.h>

struct course {

   int marks;

   char subject[30];

};

 

int main() {

   struct course *ptr;

   int i, noOfRecords;

   printf("Enter the number of records: ");

   scanf("%d", &noOfRecords);

 

   // Memory allocation for noOfRecords structures

   ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));

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

       printf("Enter the name of the subject and marks respectively:\n");

       scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);

   }

 

   printf("Displaying Information:\n");

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

       printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);

 

   return 0;

}

Comments