Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of pointer in C

Tags:

c

pointers

sizeof

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

like image 614
Matt Avatar asked Mar 18 '12 16:03

Matt


People also ask

Can we determine the size of pointer in C?

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.

What is the size of * p in C?

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.

Why size of pointer is 4 byte?

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.


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.

like image 174
Jonathan Leffler Avatar answered Sep 28 '22 11:09

Jonathan Leffler


This should do the trick:

sizeof(void*)
like image 36
John Zwinck Avatar answered Sep 28 '22 10:09

John Zwinck


char *ptr;
char **ptr2 = malloc(sizeof(ptr));

should be able to achieve your purpose. No matter what the platform is, this code should work.

like image 37
Gurpreet Singh Avatar answered Sep 28 '22 11:09

Gurpreet Singh