问题
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);
回答1:
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.
回答2:
The best way of declaring a pointer is
T *ptr;
where T
is the base type being pointed to -- int
, char
, struct foo
, whatever. malloc
returns a void *
, which is implicitly converted to the target pointer type, so all of the following are equally valid:
char *str = malloc(512); // allocates space for 512 chars
int *arr = malloc(sizeof *arr * 512); // allocates space for 512 ints
struct foo *farr = malloc(sizeof *farr * 512); // allocates space for 512 struct foos
int (*arr2)[10] = malloc (sizeof *arr2 * 512); // allocates space for 512x10 ints
etc., etc., etc.
There is no single pointer data type in C; there are multiple "pointer to T
" data types. Pointer arithmetic depends on the base type; str + 1
will yield a different value from arr + 1
, which will yield a different value from farr + 1
, etc. void *
is the "generic" pointer type, but you don't want to use generic pointers for everything.
Do not hide pointer types behind typedefs, unless the pointer type is meant to be opaque and never dereferenced, and even then it's usually a bad idea.
来源:https://stackoverflow.com/questions/10108605/which-type-should-i-use-for-a-pointer-ptrdiff-t-or-void