Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the size of a pointer is 4bytes in C++

Tags:

c++

On the 32-bit machine, why the size of a pointer is 32-bit? Why not 16-bit or 64-bit? What's the cons and pros?

like image 354
skydoor Avatar asked Mar 11 '10 21:03

skydoor


People also ask

Why char pointer is 4 bytes?

A pointer in this case is 4 bytes because a 32bit processor uses 32 bit addresses so it can address 232 discrete memory locations (4Gb).

Are all pointers 4 bytes?

Note that all pointers are 8 bytes.

Why size of pointer is 8 bytes in C?

Pointer in C is just a variable that could store the address of the other variable. In C size of a pointer is not fixed as it depends on Word size of the processor. In general a 32 bit computer machine then size of a pointer would be 4 bytes while for a 64 bit computer machine it would be 8 bytes.


2 Answers

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. On most 32 bit machines, 32 bits were enough to address all the memory, so that's what the pointer size was in C++. I know that some of the early M68000 series chips only had a 24 bit memory address space, but it was addressed from a 32 bit register so even on those the pointer would be 32 bits.

In the bad old days of the 80286, it was worse - there was a 16 bit address register, and a 16 bit segment register. Some C++ compilers didn't hide that from you, and made you declare your pointers as near or far depending on whether you wanted to change the segment register. Mercifully, I've recycled most of those brain cells, so I forget if near pointers were 16 bits - but at the machine level, they would be.

like image 129
Paul Tomblin Avatar answered Oct 01 '22 00:10

Paul Tomblin


The size of a pointer in C++ is implementation-defined. C++ might run on anything from your toaster's chip up to huge mainframes. Different architectures require different sizes of the data types.

If on your implementation a pointer is 32bit, then that's very likely an architecture which can address 2^32 bytes. (Note that even the size of bytes might be different depending on the implementation.) 64bit architectures generally can address 2^64 bytes, so implementations on these architectures will likely have a pointer size of 64bit.

like image 32
sbi Avatar answered Oct 01 '22 02:10

sbi