(void *) - what is it used for?

I tried to find this on SO, but I think that because of the syntax and I don’t know exactly what to look for, I peeled off a bit.

I saw (void *) which is used to create, usually to call functions. What is it used for?

+4
source share
4 answers

void* , commonly called a void pointer , is a generic type of pointer that can point to an object of any type. Pointers to different types of objects are almost identical in memory, so you can use void pointers to avoid type checking, which would be useful when writing functions that process several data types.

Void pointers are more useful with C than C ++. Normally, you should avoid using void pointers and use function overloading or templates instead. Type checking is good!

+3
source

The void pointer is a pointer to a value whose type and size are unknown. I will give an example of how it can be used in C - although other commentators are correct, saying that by and large it should not be used (and, in fact, not needed) in C ++.

Suppose you have a structure in which a key and a value are stored. It can be defined as follows:

 typedef struct item_t { char *key; int value; } item_t; 

Thus, you can use this structure to match any string key with an integer value. But what if you want to keep some arbitrary value? Maybe you want some keys to correspond to integers, and some keys to correspond to doubles? You must define your structure so that it tracks (using a pointer) a value of an arbitrary type and size. void * is suitable for the account in this case:

 typedef struct item_t { char *key; void *value; } item_t; 

Now, if your value is int, you can get its value with (int *) value , or if its value is double, you can do it with (double *) value . This assumes, of course, that the code using the structure knows what type it expects to see in which context.

However, in C ++ the same functionality is usually achieved not with void * , but with the use of things like templates or a superclass from which all your types go off (for example, Object in Java), the list of objects can store some lines, some Integer and etc.).

+3
source

This is the most common way to provide an object pointer in C / C ++. Like an object in C # or Java

+1
source

This is most often used when you want to pass a parameter that may have different states.

For example, in your general code, you pass void * as a parameter, and then in the "Specific" implementation of this code, you must cast void * to whatever you want

Common code abc.h

 void Test(void* pHandle); 

Windows code abc.Cpp

 void Test(void* phandle) { WindowsStructure* myStruct = (WindowsStructure*)(pHandle); myStruct->getWhatINeed; } 

Linux code abc.Cpp

 void Test(void* phandle) { LinuxStructure* myStruct = (LinuxStructure*)(pHandle); myStruct->getWhatINeed; } 
+1
source

Source: https://habr.com/ru/post/1483868/


All Articles