简体   繁体   中英

How to Convert Void* into size_t?

I have the following function:

size_t calc_allign(size_t num) {
    return ((num + 7) & (-8)) - num;
}

And want to use it like this:

int start_allign = calc_align (sbrk(0));

But I am getting error:

error: no matching function for call to 'calc_align'
candidate function not viable: cannot convert argument of incomplete type 'void *' to 'size_t' (aka 'unsigned long') for 1st argument
size_t calc_align(size_t num) {

How may I convert void* ie a pointer to number? is that even something legal?

How may I convert void* ie a pointer to number?

You can reinterpret_cast a pointer type to std::uintptr_t (or the signed equivalent). You can then further convert to another integer type such as std::size_t and that conversion can be implicit. In theory, the latter conversion may be lossy on systems where std::size_t is a smaller type.

However, as far as the C++ language is concerned, there are no guarantees about the resulting number other than converting it back from std::uintptr_t to the same pointer type will result in the same pointer value.

plus can you show some code?

Example:

void* ptr = sbrk(0);
auto numptr = reinterpret_cast<std::uintptr_t>(ptr);
static_assert(sizeof(std::size_t) >= std::uintptr_t,
    "Sorry, it isn't possible to represents pointers using std::size_t on this system");
std::size_t example = numptr;

auto ptr2 = reinterpret_cast<void*>(numptr);
assert(ptr2 == ptr); // guaranteed to pass

why reinterpret_cast not (uintptr_t)?

The behaviour of explicit conversion aka C-style cast depend on the type of the operand. Some casts are unsafe while others are benign. Often simple mistakes cause intended safe cast to be unintendedly unsafe, leading to undefined behaviour (which is very bad) - while the proper C++ style cast would result in compilation error, leading to detection of the mistake (which is very good).

In case of reinterpret_cast, we are doing such unsafe cast so there is no safety aspect, but instead the importance of C++ style cast is to communicate that lack of safety to the reader of the program.

Don't use the C-style casts in C++. You don't need them for anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM