Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof a pointer

Tags:

c++

sizeof

int i=0;
int *p = &i;
std::cout<<sizeof(i)<<" vs "<<sizeof(p)<<"\n";

char c='0';
char*pc = &c;
std::cout<<sizeof(c)<<" vs "<<sizeof(pc)<<"\n";

double d=0.123456789;
double *pd = &d;
std::cout<<sizeof(d)<<" vs "<<sizeof(pd)<<"\n";

Why is the size of a pointer always equal to that of an integer which is 4?

like image 417
Sysss Enginerss Avatar asked Dec 01 '25 08:12

Sysss Enginerss


2 Answers

Pointers don't contain the data they point to.

Pointers just point to the data they point to.

sizeof( double* ) is the size of the data used to describe where a double is located. Much as a piece of paper with a house address on it doesn't change size if the house is bigger or smaller, the size of a pointer is not a function of the size of the data pointed to.

Well, usually. You could imagine international addresses being longer, and requiring more paper. Similarly, you could imagine addresses inside an apartment building requiring an extra line for "unit number" compared to addresses elsewhere, or even "in-apartment" addresses that only contain the "unit number" and are thus shorter. The standard allows the size of pointers to various types to vary, and some architectures (8086 most famously) has the concept of both near and far pointers (being 16 and 32 bits respectively).

This isn't common anymore (except maybe with member function pointers, but how common are those?)

like image 120
Yakk - Adam Nevraumont Avatar answered Dec 02 '25 21:12

Yakk - Adam Nevraumont


A pointer is actually a variable containing an address. On a 32-bit machine, the address is always 32-bit, so it's 4 bytes. The same logic for 16-bit or 64-bit machines.

Just looked into the C99 standard and it says:

The size of a pointer is not necessarily the same as the size of any integer type. An implementation may support more than one size of pointer.

Well, thus I think the safest way to know a pointer's size is sizeof().


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!