我应该使用哪种类型的指针? ptrdiff_t的或无效*? [英] Which type should I use for a pointer ? ptrdiff_t or void*?
问题描述
这行是定义一个指针正确的(最好的)的方式?
的typedef ptrdiff_t的指针; //指针ptrdiff_t型。 - 要么 - 无效的typedef *指针; //指针为void *。
指针PTR =的malloc(1024);
指针在C是类型 T *
,其中 T
的类型是指向; 无效*
是通用的指针类型。通常情况下,你令C隐式转换无效*
有用的东西,例如
的char *缓冲区=的malloc(1024);
ptrdiff_t的
是两个指针相减,例如
ptrdiff_t的D = write_ptr - 缓冲;
//现在你知道了write_ptr超出了缓冲区的开始d字节
ptrdiff_t的
是一个整数类型,而不是一个指针类型;你不能使用间接运算符 *
就可以了。 (你也不能有意义使用它在一个无效*
,顺便说一句。)
假如你想一个指针存储在一个整数类型, uintptr_t形式
将是适当的。
Which line is the correct (best) way for defining a pointer?
typedef ptrdiff_t pointer; // pointers are ptrdiff_t.
-- or --
typedef void* pointer; // pointers are void*.
pointer ptr = malloc(1024);
Pointers in C are of type T*
where T
is the type pointed to; void*
is the generic pointer type. Usually, you let C implicitly convert void*
to something useful, e.g.
char *buffer = malloc(1024);
ptrdiff_t
is the type returned by the subtraction of two pointers, e.g.
ptrdiff_t d = write_ptr - buffer;
// now you know the write_ptr is d bytes beyond the start of the buffer
ptrdiff_t
is an integral type, not a pointer type; you cannot use the indirection operator *
on it. (Nor can you meaningfully use it on a void*
, by the way.)
Had you wanted to store a pointer in an integer type, uintptr_t
would have been appropriate.
这篇关于我应该使用哪种类型的指针? ptrdiff_t的或无效*?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!