Void Pointer

The void pointer has no data type and can assigned to the memory address of ANY data type.

 

aka Generic Pointer.

 

Declared just like any other pointer:  void *vPtr ;

 

Or declared and initialised:  void *vPtr = &myVar ;

 

#include<stdio.h>

int main() {
	int myInt = 17 ;        //declare an int
	float myFlt = 42 ;      //declare a float
	void *vPtr ;            //declare a void pointer

	vPtr = &myInt ;         //assign address of myInt to the void pointer
	printf("Address of myInt: %p \n", vPtr) ;

	int *pInt ;             //declare an int pointer
	pInt = vPtr ;           //assign contents of void pointer to int pointer
							//now dereference to display value
	printf("Value of myInt, via void pointer: %d \n", *pInt) ;

	vPtr = &myFlt ;         //assign address of myFlt to the void pointer
	printf("Address of myFlt: %p \n", vPtr) ;

	float *pFlt ;           //declare a float pointer
	pFlt = vPtr ;           //assign contents of void pointer to float pointer
							//now dereference to display value
	printf("Value of myFlt, via void pointer: %f \n", *pFlt) ;

	return 0;
}

Compile & Run:

Address of myInt: 0x28ac64
Value of myInt, via void pointer: 17
Address of myFlt: 0x28ac60
Value of myFlt, via void pointer: 42.000000

 

 

Cannot dereference a void pointer.

 

*vPtr = 22 ;  //will not work!

 

Unless it is cast:

 

*(int *)vPtr = 36 ;  //here, the void pointer is being cast first of all

 

#include<stdio.h>

int main() {
	int myInt = 17 ;		//define an int
	void *vPtr = &myInt;	//define a void pointer to myInt

	//*vPtr = 22;			//will not work
	*(int *)vPtr = 36;		//has to be cast
	printf("myInt: %d \n", myInt) ;

    return 0;
}

Compile & Run:

myInt: 36

Leave a Reply