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.