Go Back

Operations on Pointers and Concept of dynamic memory allocation

11/17/2023
All Articles

#Operations on Pointers Concept of dynamic memory allocation

Operations on Pointers and Concept of dynamic memory allocation

Operations on Pointers and Concept of dynamic memory allocation

Below is list of operation in pointer:

The address-of operator & is used to get the memory address of a variable.

#include <stdio.h>
int main()
{
   int a=10;    //variable declaration
   int *p;      //pointer variable declaration
   p=&a;        //store address of variable a in pointer p
   printf("Address stored in a variable p is:%x\n",p);  //accessing the address
   printf("display value stored in a variable p is:%d\n",*p);   //accessing the value
   return 0;
}



Null Pointer
We can create a null pointer by assigning null value during the pointer declaration. This method is useful when you do not have any address assigned to the pointer. A null pointer always contains value 0.

Following program illustrates the use of a null pointer:

#include <stdio.h>
int main()
{
    int *p = NULL;     //null pointer
    printf(“display value inside variable p is:\n%x”,p);
    return 0;
}


Wild pointer
A pointer is said to be a wild pointer if it is not being initialized to anything

#include <stdio.h>
int main()
{
int *p;     //wild pointer
printf("\n%d",*p);
return 0;
}

Dynamic Memory Allocation:


Pointers are commonly used in dynamic memory allocation with functions like malloc, calloc, and realloc.

Example:


int *dynamicArray = (int *)malloc(5 * sizeof(int));


#include <stdio.h>
#include <stdlib.h>

int main() {
    // Allocate memory for an integer array
    int *arr = (int *)malloc(5 * sizeof(int));

    if (arr == NULL) {
        printf("display Memory allocation failed.\n");
        return 1; // Exit with an error code
    }

    // Initialize the array
    for (int i = 0; i < 5; ++i) {
        arr[i] = i * 2;
    }

    // Print the array elements
    for (int i = 0; i < 5; ++i) {
        printf("%d ", arr[i]);
    }

    // Deallocate the allocated memory
    free(arr);

    return 0;
}

this are function malloc or calloc is not NULL. Also, after using dynamically allocated memory, it's crucial to free it using free to avoid memory leaks.


Here's an overview of these functions:

  • malloc (Memory Allocation): malloc stands for "memory allocation." It is used to allocate a specified number of bytes of memory.
     
  • calloc (Contiguous Allocation): calloc is used to allocate a specified number of blocks of memory, each with a specified number of bytes.
     
  • realloc (Reallocate Memory): realloc is used to change the size of the memory block previously allocated using malloc or calloc
     
  • free (Free Allocated Memory): free is used to deallocate the memory block previously allocated using malloc, calloc, or realloc.

Article