Pointer in C programming

 

Introduction

Ø When we define and initialize a variable at that time we come to know about these things:

Ø  Memory block i.e. variable get some space in RAM and we can think of that as a block.

Ø  Name of memory block or Variable’s name

Ø  Content of that block i.e. value in that variable

Ø  Address of memory block i.e. unique address which allows us to access that variable.

Ø  We can print address of any variable by using printf function as : printf(“%d”,&variable_name);

Ø  Pointers are one of the core components of the C programming language.

Ø  A pointer can be used to store the memory address of other variables, functions, or even other pointers.

Ø  The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C.

Ø  A pointer is defined as a derived data type that can store the address of other C variables or a memory location.

Ø  We can access and manipulate the data stored in that memory location using pointers.

Ø  As the pointers store the memory addresses, their size is independent of the type of data they are pointing to.

Ø  This size of pointers only depends on the system architecture.

            Syntax:

Ø  The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration.

Ø  datatype * ptr;

Ø  Where,

Ø  ptr is the name of the pointer.

Ø  datatype is the type of data it is pointing to.

Ø  The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures, etc.

The Address(&) and Indirection(*) Operators

Ø  Address of Operator (&) :

Ø  Operand must be the name of the variable.

Ø   & operator gives address no. of variable.

Ø  & is also known as “Referencing Operator”.

Ø  Indirection Operator (*):

Ø  It is also known as “Dereferencing Operator”.

Ø  It takes address as an argument.

Ø   * returns the content/container whose address is it’s argument. 

How to Use Pointers?

Ø  The use of pointers can be divided into three steps:

Ø  Pointer Declaration

Ø  Pointer Initialization

Ø  Dereferencing

Ø  Pointer Declaration

Ø  In pointer declaration, we only declare the pointer but do not initialize it.

Ø  To declare a pointer, we use the ( * ) dereference operator before its name.

Ø  Example: int *ptr;

Ø  The pointer declared here will point to some random memory address as it is not initialized.

Ø  Such pointers are called wild pointers.

Ø  Pointer Initialization

Ø  Pointer initialization is the process where we assign some initial value to the pointer variable.

Ø  We generally use the ( & ) addressof operator to get the memory address of a variable and then store it in the pointer variable.

Ø  Example:

Ø  int var = 10;

Ø  int * ptr;

Ø  ptr = &var;

Ø  We can also declare and initialize the pointer in a single step.

Ø  This method is called pointer definition as the pointer is declared and initialized at the same time.

Ø  Example: int *ptr = &var;

Ø  Dereferencing

Ø  Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer.

Ø  We use the same ( * ) dereferencing operator that we used in the pointer declaration.

WAP to illustrate pointers.

            #include <stdio.h>

            void pointer() {

                int var = 10;

                int *ptr;

                // note that data type of ptr and var must be same

                ptr = &var;

                printf("Value at ptr = %p \n", ptr);

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

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

            }

            int main()

            {

                pointer();

                return 0;

            }

Pointer to Pointer (Double pointer)

Ø  The pointer to a pointer in C is used when we want to store the address of another pointer.

Ø  The first pointer is used to store the address of the variable.

Ø   And the second pointer is used to store the address of the first pointer.

Ø  That is why they are also known as double-pointers.

Ø  We can use a pointer to a pointer to change the values of normal pointers or create a variable-sized 2-D array.

Ø  A double pointer occupies the same amount of space in the memory stack as a normal pointer.


Declaration of Pointer to a Pointer in C

Ø  Declaring Pointer to Pointer is similar to declaring a pointer in C.

Ø  The difference is we have to place an additional ‘*’ before the name of the pointer.

Ø  Syntax:

Ø  data_type_of_pointer **name_of_variable = & normal_pointer_variable;

Ø  Example:

Ø  int val = 5;

Ø  int *ptr = &val;    // storing address of val to pointer ptr.

Ø  int **d_ptr = &ptr; // pointer to a pointer declared which is pointing to an integer.

WAP to simulate the pointer to pointer.

            #include <stdio.h>

            int main() {

                int a = 5;

                int* ptr2 = &a;

                int** ptr1 = &ptr2;

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

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

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

                printf("address of a: %x\n",ptr2);  

                printf("address of ptr2: %x\n",ptr1);

                return 0;

            }

Application of Double Pointers in C

Ø  They are used in the dynamic memory allocation of multidimensional arrays.

Ø  They can be used to store multilevel data such as the text document paragraph, sentences, and word semantics.

Ø  They are used in data structures to directly manipulate the address of the nodes without copying.

Ø  They can be used as function arguments to manipulate the address stored in the local pointer.

Pointer Expressions

Ø  C supports a rich set of built-in operations like arithmetic, relational, assignment, conditional, etc. which can be performed on identifiers.

Ø  Just like any other variable, these operations can be also performed on pointer variables.

Ø  Pointer Expressions in C:

Ø  Arithmetic operators

Ø  Relational operators

Ø  Assignment operators

Ø  Conditional operators

Ø  Unary operators

Ø  Bitwise operators

Ø  We can perform arithmetic operations to pointer variables using arithmetic operators.

Ø  We can add an integer or subtract an integer using a pointer pointing to that integer variable. 

Ø  Example:

Ø  *ptr1 + *ptr2

Ø  *ptr1 * *ptr2

Ø  *ptr1 + *ptr2 - *ptr3

Ø  We can also directly perform arithmetic expressions on integers by dereferencing pointers. Let’s look at the example given below where p1 and p2 are pointers.

Ø  *p1 + 10,     *p2 - 5,     *p1 - *p2 + 10,      *p1/2

Program showing pointer expressions during Arithmetic Operations

            #include <stdio.h>

            int main() {

                int a = 20, b = 10;

                int add, sub, div, mul, mod;

                int *ptr_a, *ptr_b;

                ptr_a = &a;

                ptr_b = &b;

                add = *ptr_a + *ptr_b;

                sub = *ptr_a - *ptr_b;

                mul = *ptr_a * *ptr_b;

                div = *ptr_a / *ptr_b;

                mod = *ptr_a % *ptr_b;

                printf("Addition = %d\n", add);

                printf("Subtraction = %d\n", sub);

                printf("Multiplication = %d\n", mul);

                printf("Division = %d\n", div);

                printf("Modulo = %d\n", mod);

                return 0;

            }

Program to find biggest among three numbers using pointer.

            #include<stdio.h>

            int main() {

             int a,b,c,*pa, *pb, *pc;

             printf("Enter three numbers:\n");

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

             pa= &a;

             pb= &b;

             pc= &c;

             if(*pa > *pb && *pa > *pc)

             {

              printf("Largest is: %d", *pa);

             }

            else if(*pb > *pc && *pb > *pc)

             {

              printf("Largest is : %d", *pb);

             }

             else

             {

              printf("Largest = %d", *pc);

             }

             return 0;

            }

Pointer Arithmetic

Ø  Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers.

Ø  The pointer variables store the memory address of another variable.

Ø  It doesn’t store any value. 

Ø  Hence, there are only a few operations that are allowed to perform on Pointers in C language.

Ø  The C pointer arithmetic operations are slightly different from the ones that we generally use for mathematical calculations.

Ø  These operations are:

Ø  Increment/Decrement of a Pointer

Ø  Addition of integer to a pointer

Ø  Subtraction of integer to a pointer

Ø  Subtracting two pointers of the same type

Ø  Comparison of pointers

Increment/Decrement of a Pointer

Ø  Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. 

Ø  For Example:

Ø  If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int), and the new address will point to 1004.

Ø  While if a float type pointer is incremented then it will increment by 4(size of a float) and the new address will be 1004.

Ø  Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the number equal to the size of the data type for which it is a pointer.

Ø  For Example:

Ø  If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an int), and the new address will point to 996.

Ø  While if a float type pointer is decremented then it will decrement by 4(size of a float) and the new address will be 996.

Progam to simulate Increment/Decrement of a Pointer

            #include <stdio.h>

            int main() {

                int a = 22;

                int *p = &a;

                printf("p = %u\n", p);

                p++;

                printf("p++ = %u\n", p);

                p--;

                printf("p-- = %u\n", p);

             

                char c = 'a';

                char *r = &c;

                printf("r = %u\n", r);

                r++;

                printf("r++ = %u\n", r);  

                r--;

                printf("r-- = %u\n", r);  

                return 0;

            }

Addition of Integer to Pointer

Ø  When a pointer is added with an integer value, the value is first multiplied by the size of the data type and then added to the pointer.

Ø  For Example:

Ø  Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address.

Ø  If we add integer 5 to it using the expression, ptr = ptr + 5, then, the final address stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.

 C program to illustrate pointer Addition

            #include <stdio.h>

            int main() {

                int N = 4;

                int *ptr2;

                ptr2 = &N;

                printf("Pointer ptr2 before Addition: ");

                printf("%p \n", ptr2);

                ptr2 = ptr2 + 3;

                printf("Pointer ptr2 after Addition: ");

                printf("%p \n", ptr2);

                return 0;

            }

Subtraction  of Integer to Pointer

Ø  When a pointer is subtracted with an integer value, the value is first multiplied by the size of the data type and then subtracted from the pointer similar to addition.

Ø  For Example:

Ø  Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.

C program to illustrate pointer subtraction

#include<stdio.h>

int main() {

    int N = 4;

    int *ptr2;

    ptr2 = &N;

    printf("Pointer ptr2 before Subtraction: ");

    printf("%p \n", ptr2);

    ptr2 = ptr2 - 3;

    printf("Pointer ptr2 after Subtraction: ");

    printf("%p \n", ptr2);

    return 0;

}

Subtraction of Two Pointers

Ø  The subtraction of two pointers is possible only when they have the same data type.

Ø  The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type.

Ø  The subtraction of two pointers gives the increments between the two pointers. 

Ø  For Example: 

Ø  Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted.

Ø  The difference between addresses is 4 bytes.

Ø  Since the size of int is 4 bytes, therefore the increment between ptr1 and ptr2 is given by (4/4) = 1.

C program to illustrate Subtraction of two pointers

            #include <stdio.h>

            int main() {

                int x = 6;

                int N = 4;

                int *ptr1, *ptr2;

                ptr1 = &N;

                ptr2 = &x;

                printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);

                x = ptr1 - ptr2;

                printf("Subtraction of ptr1 & ptr2 is %d\n",x);

                return 0;

            }

Comparison of Pointers

Ø  We can compare the two pointers by using the comparison operators in C.

Ø  We can implement this by using all operators in C >, >=, <, <=, ==, !=.

Ø  It returns true for the valid condition and returns false for the unsatisfied condition. 

            Step 1: Initialize the integer values and point these integer values to the pointer.

            Step 2: Now, check the condition by using comparison or relational operators on pointer variables.

            Step 3: Display the output.

C Program to illustrare pointer comparision

            #include <stdio.h>

            int main() {

                int arr[5];

                int* ptr1 = &arr;

                int* ptr2 = &arr[0];

                if (ptr1 == ptr2) {

                    printf("Pointer to Array Name and First Element are Equal.");

                }

                else {

                    printf("Pointer to Array Name and First Element are not Equal.");

                }

                return 0;

            }

Comparison to NULL

Ø  A pointer can be compared or assigned a NULL value irrespective of what is the pointer type.

Ø  Such pointers are called NULL pointers and are used in various pointer-related error-handling methods.

#include <stdio.h>

int main() {

   int* ptr = NULL;

    if (ptr == NULL) {

        printf("The pointer is NULL");

   }

    else {

        printf("The pointer is not NULL");

    }

    return 0;

}

Passing Pointer to a Function

Ø  When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value.

Ø  So any change made by the function using the pointer is permanently made at the address of passed variable.

Ø  This technique is known as call by reference in C.

Pointer and Array

Ø  the name of an array, is actually a pointer to the first element of the array.

Ø  The memory address of the first element is the same as the name of the array:

Ø  This basically means that we can work with arrays through pointers!

Ø  Example:

Ø  int myNumbers[4] = {25, 50, 75, 100};

Ø  printf("%p\n", myNumbers);

Ø  printf("%p\n", &myNumbers[0]);

Ø  Since myNumbers is a pointer to the first element in myNumbers, you can use the * operator to access it:

Ø  int myNumbers[4] = {25, 50, 75, 100};

Ø  // Get the value of the first element in myNumbers

Ø  printf("%d", *myNumbers);

Ø  To access the rest of the elements in myNumbers, you can increment the pointer/array (+1, +2, etc):

Ø  int myNumbers[4] = {25, 50, 75, 100};

Ø  // Get the value of the second element in myNumbers

Ø  printf("%d\n", *(myNumbers + 1));

Ø  // Get the value of the third element in myNumbers

Ø  printf("%d", *(myNumbers + 2));

Ø  // and so on..

Ø  Or loop through it:

#include<stdio.h>

int main() {

int myNumbers[4] = {25, 50, 75, 100};

int *ptr = myNumbers;

int i;

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

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

}

return 0;

}

Ø  It is also possible to change the value of array elements with pointers:

Ø  int myNumbers[4] = {25, 50, 75, 100};

Ø  // Change the value of the first element to 13

Ø  *myNumbers = 13;

Ø  // Change the value of the second element to 17

Ø  *(myNumbers +1) = 17;

Ø  // Get the value of the first element

Ø  printf("%d\n", *myNumbers);

Ø  // Get the value of the second element

Ø  printf("%d\n", *(myNumbers + 1));

Write a program to find the sum of all the elements of an array using pointers.

            #include <stdio.h>

            int main() {

              int i, x[6], sum = 0;

              printf("Enter 6 numbers: ");

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

                  scanf("%d", x+i);      // Equivalent to scanf("%d", &x[i]);

                  sum += *(x+i);            // Equivalent to sum += x[i]

              }

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

              return 0;

            }

Array of Pointer

Ø  When we want to point at multiple variables or memories of the same data type in a C program, we use an array of pointers.

Ø  Application of Arrays of Pointers

Ø  Let us assume that we want to build an enclosed system, and this system uses a different kind of thermometer for measuring the temperature.

Ø  Now, in this case, we can use an array for holding the address of memory for every sensor.

Ø  This way, manipulation of the sensor status becomes very easy.

Ø  Example

Ø  The thermo[0] will be holding the 1st sensor’s address.

Ø  The thermo[1] will be holding the 2nd sensor’s address and so on.

Ø  Now, since it’s an array, it can interact directly with the thermo pointer indexed in the array. Thus, we will get the 1st sensor’s status with the thermo[0], the second one using the thermo[1], and so on ahead.

Declaration of an Array of Pointers in C

Ø  An array of pointers can be declared just like we declare the arrays of char, float, int, etc.

Ø  The syntax for declaring an array of pointers would be:

Ø  data_type *name_of_array [array_size];

Ø  Now, let us take a look at an example for the same,

Ø  int *ary[55];

Ø  This one is an array of a total of 55 pointers.

Ø  In simple words, this array is capable of holding the addresses a total of 55 integer variables.

Ø  Think of it like this- the ary[0] will hold the address of one integer variable, then

Ø  the ary[1] will hold the address of the other integer variable, and so on.

Program that demonstrates how one can use an array of pointers in C

            #include<stdio.h>

            int main()  {

                  int *arr[3];

                  int p = 40, q = 60, r = 90, i;

                  arr[0] = &p;

                  arr[1] = &q;

                  arr[2] = &r;

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

                           printf(“For the Address = %d\t the Value would be = %d\n”, arr[i], *arr[i]);

                  }

                  return 0;

            }

            Program that demonstrates how one can use an array of pointers in C

            #include <stdio.h>

            int main() {

                int var1 = 10;

                int var2 = 20;

                int var3 = 30;

                // array of pointers to integers

                int* ptr_arr[3] = { &var1, &var2, &var3 };

                // traversing using loop

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

                    printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);

                }

                return 0;

            }

            Pointer and String

            A pointer to a string in C can be used to point to the base address of the string array, and its value can be dereferenced to get the value of the string.

            To get the value of the string array is iterated using a while loop until a null character is encountered.

            Instead of using arrays, we can use character pointers to store a string value.

            Creating a Pointer for the String

            We can create a character pointer to string in C that points to the starting address of the character array.

            This pointer will point to the starting address of the string, that is the first character of the string, and we can dereference the pointer to access the value of the string.

            // character array storing the string 'String'

            char str[7] = "String";

            // pointer storing the starting address of the character array str

            char *ptr = str;

            Accessing String via a Pointer

            An array is a contiguous block of memory, and when pointers to string in C are used to point them, the pointer stores the starting address of the array.

            Similarly, when we point a char array to a pointer, we pass the base address of the array to the pointer.

            The pointer variable can be dereferenced using the asterisk * symbol in C to get the character stored in the address. For example,

            char arr[] = "Hello";

            char *ptr = arr;

            printf("%c ", *ptr);            // H

            printf("%c ", *(ptr + 1));    // e

            printf("%c ", *(ptr + 2));    // l

            printf("%c ", *(ptr + 3));    // l

            printf("%c ", *(ptr + 4));    // o

             

            #include<stdio.h>

            int main() {

                char str[11] = "HelloWorld";

                char *ptr = str;

                while (*ptr != '\0') {

                    printf("%c", *ptr);

                    ptr++;

                }

                return 0;

            }

            Using a Pointer to Store String

            #include<stdio.h>

            int main() {

                char *strPtr = "HelloWorld";

                char *temp = strPtr;

                while (*temp != '\0') {

                    printf("%c", *temp);

                    temp++;

                }

                return 0;

            }

            Array of Strings

 Ø  For 2-D arrays, both the dimensions of the array need to be defined at the time of variable declaration, and our strings don't have to be of the same length.



Ø  From the figure, we can see each string in the array has addresses that are not utilised that are cells marked with cells filled with red color.

Ø  To solve the problem of memory wastage, we can use pointers of size four that can be used to store strings of variable size.

Ø  In this case, each string takes the memory equal to the string length (inclusive of the null character), preventing memory wastage like in the case of a 2-D array.

Ø  Here, str[i] represents the base address of the ith string.

            #include<stdio.h>

            int main() {

                char *str[4] = {"String","Topics","Hello","World"};

                int i;

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

                    int j = 0;

                    while (*(str[i] + j) != '\0') {

                        printf("%c", *(str[i]+j));

                                    j++;

                    }

                    printf("\n");

                }

                return 0;

            }

C program for Pointers with Strings

            #include<stdio.h>

            int main() {

                char subjects[5][20];

                int i, j;

                printf("Enter five different subjects\n");

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

                    scanf("%s", subjects[i]);

                }

            printf("The name of subjects are \n");

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

                    j = 0;

                    while (*(subjects[i] + j) != '\0') {

                        printf("%c", *(subjects[i] + j));

                        j++;

                    }

                    printf(" <- size = %d\n", j);

                }

                return 0;

            }

 Dynamic Memory Allocation

Ø  Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.

Ø  C provides some functions to achieve these tasks.

Ø  There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming.

Ø  They are:

Ø  malloc()

Ø  calloc()

Ø  free()

Ø  realloc()

C malloc() method

Ø  The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size.

Ø  It returns a pointer of type void which can be cast into a pointer of any form.

Ø  It doesn’t Initialize memory at execution time so that it has initialized each block with the default garbage value initially. 

Ø  Syntax of malloc() in C

Ø  ptr = (cast-type*) malloc(byte-size)

Ø  For Example:

Ø  ptr = (int*) malloc(100 * sizeof(int));

Ø  Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

Ø  If space is insufficient, allocation fails and returns a NULL pointer.



 C program to demonstrate malloc method

            #include <stdio.h>

            #include <stdlib.h>

            int main() {

                int* ptr;

                int n, i;

                printf("Enter number of elements:");

                scanf("%d",&n);

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

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

                if (ptr == NULL) {

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

                    exit(0);

                }

            else {

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

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

                        ptr[i] = i + 1;

                    }

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

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

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

                    }

                }

                return 0;

            }

C calloc() method

Ø  “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type.

Ø  it is very much similar to malloc() but has two different points and these are:

Ø  It initializes each block with a default value ‘0’.

Ø  It has two parameters or arguments as compare to malloc().

Ø  Syntax of calloc() in C

Ø  ptr = (cast-type*)calloc(n, element-size);

Ø  here, n is the no. of elements and element-size is the size of each element.

Ø  For Example:

Ø  ptr = (float*) calloc(25, sizeof(float));

Ø  This statement allocates contiguous space in memory for 25 elements each with the size of the float.


C program to demonstrate calloc method

            #include <stdio.h>

            #include <stdlib.h>

            int main() {

                int* ptr;

                int n, i;

                n = 5;

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

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

                if (ptr == NULL) {

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

                    exit(0);

                }

            else {

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

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

                        ptr[i] = i + 1;

                    }

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

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

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

                    }

                }

                return 0;

            }

            C free() method

            “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 of free() in C

            free(ptr);


C program to demonstrate free method

            #include <stdio.h>

            #include <stdlib.h>

            int main() {

                int *ptr, *ptr1;

                int n, i;

                n = 5;

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

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

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

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

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

                    exit(0);

                }

            else {

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

                    free(ptr);

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

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

                    free(ptr1);

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

                }

                return 0;

            }

C realloc() method

Ø  “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory.

Ø  In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.

Ø  re-allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value.

Ø  Syntax of realloc() in C

Ø  ptr = realloc(ptr, newSize);

Ø  where ptr is reallocated with new size 'newSize'.


C program to demonstrate realloc method

            #include <stdio.h>

            #include <stdlib.h>

            int main() {

                int* ptr;

                int n, i,new_size;

                n = 5;

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

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

                if (ptr == NULL) {

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

                    exit(0);

                }

            else {

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

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

                        ptr[i] = i + 1;

                    }

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

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

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

                    }

                   new_size = 10;

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

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

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

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

                        ptr[i] = i + 1;

                    }

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

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

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

                    }

                    free(ptr);

                }

                return 0;

            }

            WAP to enter age of 20 students and count ages between 18 and 25 from the array using DMA functions.

            #include <stdio.h>

            #include <stdlib.h>

            int main() {

                int* student;

                int n, i,age, count = 0;

                n = 20;

                printf("Entered number of students: %d\n", n);

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

                if (student == NULL) {

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

                    exit(0);

                }

            else {

                    printf("Enter the age of students:\n");

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

                        scanf("%d",&age);

                        student[i] = age;

                    }

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

                        if(student[i]>18 && student[i]<25)

                            count++;

                    }

                    printf("the number of students between 18 and 25 is %d",count);

                }

                return 0;

            }

            WAP to find largest and smallest number in a list of N number using DMA

            #include <stdio.h>

            #include <stdlib.h>

            int main() {

                int* arr;

                int n, i,num, small, large, count = 0;

                printf("Enter the number of elements in list");

                scanf("%d",&n);

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

                if (arr == NULL) {

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

                    exit(0);

                }

            else {

                    printf("Enter the numbers in list:\n");

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

                        scanf("%d",&num);

                        arr[i] = num;

                    }

                    small = arr[0];

                    large = arr[0];

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

                    if(small>arr[i])

                        small = arr[i];

                    if(large < arr[i])

                        large = arr[i];

                }

                printf("The smallest element is %d and largest is %d",small,large);

                }

                return 0;

            }


             

 

             

 

 

             

 

 

 

 

 

 


 

No comments:

Post a Comment

Research in Social Science

   C  Concept of Research in Social Science -         Understanding the concept of Research Methods, Techniques and Tools: Interview, Fo...