Get Size of Pointer in C

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).

8

3 Answers

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.

10

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest