Void pointer
Feb 26, 2021
In c++, we can’t assign the address of a variable of one data type to a pointer of another data type.
In such a case, use a void pointer or generic pointer.
Facts:
- malloc() and calloc() returns void * type and allow this function to be used to allocate memory of any data type.
- void pointers are used to implement a generic function in c.
- void pointer can’t be dereferenced.
int main() {
int a = 10;
void *ptr = &a;
printf("%d", *ptr);
}
Output:
compile error: void* is not pointer-to-object type
4. void pointer doesn’t allow pointer arithmetic.
Program:
#include <iostream>
using namespace std;
int main()
{
void *ptr1;
struct student {
int a;
int b;
};
struct student *stud_ptr;
stud_ptr->a = 10;
stud_ptr->b = 20;ptr1 = (struct student *)malloc(sizeof(student));
ptr1 = stud_ptr;
printf("%d\n", (*(student *)ptr1).a);return 0;
}
Output
10