Size of a pointer in C

681 views Asked by At

How can I find the size of the type "pointer?" For example, if I want to know the size of an integer, I can use "sizeof(int)". What is the equivalent for a pointer? Is it possible to do this without initializing the pointer?

3

There are 3 answers

4
Matteo Italia On BEST ANSWER

sizeof(void*) generally yields the size of pointers on your architecture, although there may be architectures where pointers to specific types are smaller - since void * is guaranteed to allow a full round-trip to any data pointer (C99 §6.3.2.3 ¶1), it should be surely bigger or equal to all other data pointers.

Pointers to functions are a whole different beast, which may require more space than a plain void * (think microcontrollers, where code and data may reside in completely different address spaces). Here you can get an idea of the situation with something like sizeof(void (*)()), although IIRC nothing stops a particular implementation to have different sizes for each and every function pointer type actually, C99 §6.3.2.3 ¶8 requires that a function pointer must survive a roundtrip through any other function pointer type, so I guess it's safe to use any function pointer type to probe function pointers size in the same way as void * is a good measure for data pointers size.

1
Jens On

Try using a plain, untyped void pointer like so:

size_t sz = sizeof(void *);

Just be aware that the size of a pointer (like the size of the integer) is not the same for all architectures that your program may be compiled for.

2
M.M On

"pointer" isn't a type. It can be part of a type. "Pointer to int" would be an example of a type, and you can find the size of that by writing sizeof(int *).

Different types of pointer may have different sizes, although on modern hardware they are usually all the same.