× Home
Next Lec → ← Previous Lec

Void Pointer

What is a void pointer?

Void Pointer: C Program

  • A void pointer is a pointer that has no data type associated with it.
  • A void pointer can be easily typecasted to any pointer type
    • int x = 10;
    • char y = 'x';
    • void *p = &x; // void pointer stores address of int 'x'
    • p = &y; //void pointer now holds address of char 'y'

Uses of void pointers

  • In dynamic memory allocation, malloc() and calloc() return (void*) type pointer
  • This allows these dynamic memory functions to be used to allocate memory of any data type. This is because these pointers can be typecasted to any pointer type

More on void pointers

  • It is not possible to derefernce void pointers
    • as compiler doesn't know the data type of the variable which its going to be stored.
  • Pointer arithmetic is not allowed in C standards with void pointers
  • Hence it is not recommended to use pointer arithmetic with void pointer.
                        
                        #include <stdio.h>
                         int main()
                         {
                            int a=345;
                            float b=8.3;
                            void *ptr;
                            ptr = &a;
                            // printf("The value of a is %d",*ptr); //this is not allowed
                            printf("The value of a is %d",*((int*)ptr)); //compiler is saying that it was a void pointer before
                            //but now it is a interger pointer, so now by dereferencing it we want the value which it is pointing now
                            // we can change its value also by doing typecasting
                            ptr = &b;
                            printf("\nThe value of b is %f",*((float*)ptr));
                            return 0; 
                        }