Что за тип данных uintptr_t в языке C?

Что за тип данных uintptr_t в Си? Зачем он нужен и для чего используется?


Ответы (1 шт):

Автор решения: AlexGlebe

7.20.1.4 Integer types capable of holding object pointers
The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void , and the result will compare equal to the original pointer:
intptr_t
The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void , and the result willcompare equal to the original pointer:
uintptr_t

These types are optional.

Этот без знаковый целочисленный тип, который способен принять указатель и не потерять значение. То-есть при 64-битных процессорах, этот тип будет иметь размерность 64 бита, а в 32-битных - 32 бита.
Предназначен для удобной работы с указателями в целочисленной форме.
Эти типы опциональны и компиляторы не обязаны его предоставлять.

# include <stdio.h>
# include <stdint.h>
# include <inttypes.h>
int main(){
  double x ;
  uintptr_t p = ( uintptr_t ) & x ;
  printf("sizeof(p)=%zu\n",sizeof(p));
  printf("p=%" PRIxPTR "\n",p);
  ++ p;
  printf("p=%" PRIxPTR "\n",p);
}

sizeof(p)=8
p=7ffe33df1b0c
p=7ffe33df1b0d

инкремент прибавляет один, а в случае с указателем на тип double прибавилось бы 8. Так-же у указателей не предусмотрены битовые операции | & ^ ~ << >>. А у таких целочисленных типов можно.
Из недостатков можно отметить, что теряются классификаторы типов, таких-как const, volatile, _Atomic и restrict.

double const volatile _Atomic x ;
void const volatile _Atomic * restrict  vp = & x;
uintptr_t pvp = vp ;
→ Ссылка