Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of intptr_t?

Tags:

c++

c

pointers

I know it is an integer type that can be cast to/from pointer without loss of data, but why would I ever want to do this? What advantage does having an integer type have over void* for holding the pointer and THE_REAL_TYPE* for pointer arithmetic?

EDIT
The question marked as "already been asked" doesn't answer this. The question there is if using intptr_t as a general replacement for void* is a good idea, and the answers there seem to be "don't use intptr_t", so my question is still valid: What would be a good use case for intptr_t?

like image 496
Baruch Avatar asked Jan 28 '16 20:01

Baruch


People also ask

Why use intptr_ t?

The intptr_t and uintptr_t types are extremely useful for casting pointers when you want to do address arithmetic. They should be used instead of long or unsigned long for this purpose.

What are pointers used for?

Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.

What is a void pointer?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

What is uint32_t in C?

uint32_t is a numeric type that guarantees 32 bits. The value is unsigned, meaning that the range of values goes from 0 to 232 - 1. This. uint32_t* ptr; declares a pointer of type uint32_t* , but the pointer is uninitialized, that is, the pointer does not point to anywhere in particular.


1 Answers

The primary reason, you cannot do bitwise operation on a void *, but you can do the same on a intptr_t.

On many occassion, where you need to perform bitwise operation on an address, you can use intptr_t.

However, for bitwise operations, best approach is to use the unsigned counterpart, uintptr_t.

As mentioned in the other answer by @chux, pointer comparison is another important aspect.

Also, FWIW, as per C11 standard, §7.20.1.4,

These types are optional.

like image 192
Sourav Ghosh Avatar answered Sep 28 '22 09:09

Sourav Ghosh