Please, can you explain what are pointers to void data type and why they are used…
also please explain nullptr and its use along with it.
Pointers to void and nullptr
I was experimenting with the pointers to void… it seems that they store address and can output address by explicit conversion to void * BUT when we use cout<<*[pointer-name]…we get error… it seems they are only made to use the address…not the value associated with it.
Hi Sachin, pointers that point to nothing but are associated with a certain data type are called NULL pointers. They are declared as:
int *ptr = NULL ;
It points to nothing so its value when you print it will be 0x0. And when you will print it’s address it will give it’s memory address to you. You can try following code fragment:
int *nl = NULL ; // NULL pointer
cout << "Value = "<< nl << endl ;
cout << "Address = " << &nl << endl ;
Void Pointers are pointers who initially do not have specific data type to point. But that’s the benefit, we can use one pointer to point different kinds of entities. We can change the type of data that it points to in the code. But to print it’s value(after assigning it some value) we need to use type casting. Try the following piece of code for better understanding:
void *vd ; // Declaring a void pointer
int x=3 ;
float f = 2.56 ;vd = &x ; //We set vd to point to int data and use it in below 2 lines
cout << "Value = "<< ((int)vd) <<endl ; //To print void pointer’s value
cout << "Address = " << &vd << endl ;vd = &f ; Now we set vd to point to float data. We used one pointer 2 process 2 different data types.
cout << "Value = "<< ((float)vd) << endl ;
cout << "Address = " << &vd << endl ;
You will notice that vd’s address remain same through-ought.
Hope this helps
I am facing some issues in running the code for void pointers.
A similar problem is also in ide of coding blocks. it keeps running.
Hi Sachin,
If you look at the error carefully, you will observe that it’s saying
cast from 'void*' to 'int' loses precision [-fpermissive]
So, basically the error is trying to tell you that you can’t convert a void* i.e. a pointer to int i.e. a data type.
To correct this modify your code’s line:9 ascout << *((int*)vd) << endl;
*((int*)vd)
this is first converting the void* to int* and then printing the value which is pointed by the pointer vd.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.