Void pointer

Dineshbaburam
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:

  1. malloc() and calloc() returns void * type and allow this function to be used to allocate memory of any data type.
  2. void pointers are used to implement a generic function in c.
  3. 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

--

--