What is a void pointer?

28 Dec 2022 Balmiki Mandal 0 C Programming

Understanding Void Pointers in C Programming

A void pointer is a C convention for a raw address. The compiler has no idea what type of object a void Pointer really points to. If you write

In C programming, a void pointer is a special type of pointer that can point to objects of any data type. A void pointer does not have a specific data type associated with it, which means that it can be used to point to any type of object, including arrays, structures, and other types.

The syntax for declaring a void pointer:

void *ptr;

This declares a void pointer named ptr, which can point to any type of object. However, since the void pointer does not have a specific data type associated with it, you cannot dereference it directly. To use the void pointer, you must first cast it to a specific data type.

int *ip;
ip points to an int. If you write
void *p;

For example, if you have a void pointer that points to an integer, you can cast it to an integer pointer and then dereference it to get the value of the integer.

int x = 10;
ptr = &x;
int *iptr = (int *)ptr;
printf("%d\n", *iptr); // Output: 10```

In this example, the void pointer ptr is first assigned the address of the integer variable x. Then, it is cast to an integer pointer iptr, which can be dereferenced to get the value of x.

One of the main uses of void pointers in C programming is for memory allocation. When you allocate memory using functions like malloc or calloc, they return a void pointer that can be cast to any type of pointer based on the data type of the object you want to store in the allocated memory.

In summary, a void pointer is a special type of pointer in C programming that can point to objects of any data type. While you cannot dereference a void pointer directly, you can cast it to a specific data type and then use it like any other pointer.

p doesn’t point to a void!

  • In C and C++, any time you need a void pointer, you can use another pointer type. For example, if you have a char*, you can pass it to a function that expects a void*. You don’t even need to cast it. In C (but not in C++), you can use a void* any time you need any kind of pointer, without casting. (In C++, you need to cast it).
  • A void pointer is used for working with raw memory or for passing a pointer to an unspecified type.
  • Some C code operates on raw memory. When C was first invented, character pointers (char *) were used for that. Then people started getting confused about when a character pointer was a string, when it was a character array, and when it was raw memory.

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.