Understanding Void Pointer - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Understanding Void Pointer

Share This


The void pointer (generic pointer) is a special type of pointer that can be used to point to any data type. It is declared like a normal pointer as void *ptr;.

Let us discuss with an example.


#include <stdio.h> int main() { int i = 10; float f = 20.0; void *ptr; ptr = &i; printf("%d", (int*)ptr); ptr = &f; printf("%f", (float*)ptr); return 0; }
In the above-mentioned example, the pointer ptr is used to point to both i and f. Though their data types are different. 

Earlier we have seen that a pointer variable can point to a similar type variable. 

As the void pointer does not know what type of data it is pointing to, the void pointer must be explicitly cast to another pointer type before it is dereferenced. 

Let us try another example:


#include <stdio.h> #define INT 1 #define FLOAT 2 void absolute_value ( void *j, int *n) { if ( *n == INT) { if ( *((int*)j) < 0 ) *((int*)j) = *((int*)j) * (-1); } if ( *n == FLOAT ) { if ( *((float*)j) < 0 ) *((float*)j) = *((float*)j) * (-1); } } int main() { int i = 0, n = 0; float f = 0; printf("Press \n1 for integer \n2 for float"); printf("\nEnter the choice\n"); scanf("%d", &n); printf("\n"); if( n == 1) { scanf("%d", &i); printf("The value you have entered is %d \n",i); absolute_value(&i, &n); printf("The value after calling the function is %d \n",i); } if( n == 2) { scanf("%f", &f); printf("The value you have entered is %f \n",f); absolute_value(&f, &n); printf("The value after calling the function is %f \n",f); } else printf("Invalid entry!\n"); return 0; }




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.