I am wondering why in the following program sizeof(int)
returns a different value than sizeof(int*)
.
Here is the small program:
int main(){
std::cout<<sizeof(int)<<endl;
std::cout<<sizeof(int*)<<endl;
return 0;
}
And here is the output:
4
8
Till now I remember the size of a integer pointer is 4byte(gcc compiler). How can I check the correct size of a pointer? Is it computer dependent?
I am running ubuntu 12.04
# lsb_release -a
Distributor ID: Ubuntu
Description: Ubuntu 12.04 LTS
Release: 12.04
Codename: precise
Is the size of pointer is not constant(standard size) 8 bytes.
It turns out that on some/many computers, a byte is 8 bits and an int is 32 bits, therefore sizeof(int) == 4. It also turns out on many "32 bit" computers that a pointer can be stored in 32 bits, so therefore sizeof(char*) == sizeof(void*) == 4.
Simple: You are getting the size of the pointer types. 8 would be an appropriate size for a 64 bit application. 4 would be appropriate for a 32 bit application.
So the reason why you are seeing an int as 4 bytes (32 bits), is because the code is compiled to be executed efficiently by a 32-bit CPU. If the same code were compiled for a 16-bit CPU the int may be 16 bits, and on a 64-bit CPU it may be 64 bits.
Compiler designers tend to to maximize the performance of int arithmetic, making it the natural size for the underlying processor or OS, and setting up the other types accordingly. But the use of long int , since int can be omitted, it's just the same as long by definition.
The size of an int
and an int*
are completely compiler and hardware dependent. If you're seeing eight bytes used in an int*
, you likely have 64-bit hardware, which translates into eight bytes per pointer.
Hope this helps!
sizeof(char) == 1
There are no other guarantees(*).
In practice, pointers will be size 2 on a 16-bit system, 4 on a 32-bit system, and 8 on a 64-bit system.
The size of a pointer is system, compiler, and architecture-dependent. On 32-bit systems it will typically be 32 bits while on 64-bit systems they will typically be 64 bits.
If you're trying to store a pointer into an integer for later restoration into the pointer again you can use the type intptr_t
which is an integral type big enough to hold (I believe) normal (non-function) pointer types.
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