S
S
sddvxd2018-05-01 12:56:59
C++ / C#
sddvxd, 2018-05-01 12:56:59

Why do we need a pointer to void?

Hello! The question is very interesting - why is it still needed. Or rather, why I need it, I know - let's say we need to allocate a block of 100 bytes. There is no suitable type for this size - so we use void *. But I didn’t understand one thing - how does the compiler “allocate” these 100 bytes if, for example, I passed a piece of memory to the function? Why then did they even come up with giving types to pointers, why not use void * for everyone?

//header.h
void shower(PVOID pv){???}
//realize.cpp
PVOID pv = malloc(100);
shower(pv);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2018-05-01
@sddvxd

void* is used as a pointer to raw byte data that has no particular type.
This is usually used ...
1. In reading and writing to files and devices, when we can write absolutely any types there.
2. In "many-faced" functions that can accept data of different types (malloc/calloc, part of WinAPI and ODBC functions).
3. As a descriptor - a pointer that is not allowed to be dereferenced. In C, a pointer to an underdefined type is also often used for this, in Pascal, with other type equivalence rules, to an empty record. But only until another multifaceted function like CloseHandle appears.
4. To ensure the so-called. closures - transferring the context to the callback, from where the function that called the callback was called.

BOOL WINAPI EnumWindows(
  _In_ WNDENUMPROC lpEnumFunc,
  _In_ LPARAM      lParam
);

BOOL CALLBACK EnumWindowsProc(
  _In_ HWND   hwnd,
  _In_ LPARAM lParam
);

This LPARAM, which is usually defined as some kind of pointer, is the closure. The EnumWindows function promises to pass it to the lpEnumFunc function unchanged.
(C++ also uses virtual interfaces for this, but such a method, you understand, is language-dependent and is not suitable for a cross-language API.)
What happens on the side of the function? One of the two (we assume that the function is written in Java).
1. Either a certain device function is called, which says: “write 100 bytes”, and then the hardware is already working.
2. Either we convert void* to the type we need and work with it.
Types are given to pointers for three reasons.
1. You forgot about the "dereference pointer" operation. To dereference it, it must have a type!
2. In order not to be mistaken and not to reassign incompatible pointers.
3. For polymorphism - in C++, given delete x, we don't even have to store how many bytes are in the block, because we know the length of the type. (There are also virtual classes, but that's another matter.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question