How do I get the size of a pointer in C using sizeof
? I want to malloc some memory to store a pointer (not the value being pointed to).
The size of a pointer in C/C++ is not fixed. It depends upon different issues like Operating system, CPU architecture etc. Usually it depends upon the word size of underlying processor for example for a 32 bit computer the pointer size can be 4 bytes for a 64 bit computer the pointer size can be 8 bytes.
And on a 32-bit system, it's size will be 32-bit(4 bytes). sizeof(*p) is the size of pointer type i.e. int here. So usually int is of 32-bit long that is 4 bytes.
Because it mimics the size of the actual "pointers" in assembler. On a machine with a 64 bit address bus, it will be 64 bits. In the old 6502, it was an 8 bit machine, but it had 16 bit address bus so that it could address 64K of memory.
Given an arbitrary type (I've chosen char
here, but that is for sake of concrete example):
char *p;
You can use either of these expressions:
sizeof(p)
sizeof(char *)
Leading to a malloc()
call such as:
char **ppc = malloc(sizeof(char *));
char **ppc = malloc(sizeof(p));
char **ppc = malloc(sizeof(*ppc));
The last version has some benefits in that if the type of ppc
changes, the expression still allocates the correct space.
This should do the trick:
sizeof(void*)
char *ptr;
char **ptr2 = malloc(sizeof(ptr));
should be able to achieve your purpose. No matter what the platform is, this code should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With