Void pointer

  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);
}
compile error: void* is not pointer-to-object type
#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;
}
10

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store