Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of int and sizeof int pointer on a 64 bit machine

I was just wondering how can I know if my laptop is 64 or 32 bit machine. (it is a 64).

So, I thought about printing the following:

int main() {  printf("%d",sizeof(int)); } 

and the result was 4, which seemed weird (since it is a 64 bit machine)

But, when I printed this:

int main() {  printf("%d",sizeof(int*)); } 

the result was 8, which made more sense.

The question is:

Since I'm using a 64 bit machine, shouldn't a primitive type such as int should use 8 bytes

(64 bit) and by that sizeof int should be 8? Why isn't it so?

And why is the int* size is 8?

A bit confused here,

so thanks in advance.

like image 217
Itzik984 Avatar asked Dec 21 '13 16:12

Itzik984


People also ask

How many bytes is a pointer in 64-bit?

For example the size of a pointer in 32 bit is 4 bytes (32 bit ) and 8 bytes(64 bit ) in a 64 bit machines.

What is the return value of sizeof () in 64-bit machine?

So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.

What would be the size of an int pointer?

int is 32 bits in size. long , ptr , and off_t are all 64 bits (8 bytes) in size.


2 Answers

No, the sizeof(int) is implementation defined, and is usually 4 bytes.

On the other hand, in order to address more than 4GB of memory (that 32bit systems can do), you need your pointers to be 8 bytes wide. int* just holds the address to "somewhere in memory", and you can't address more than 4GB of memory with just 32 bits.

like image 173
ScarletAmaranth Avatar answered Sep 26 '22 19:09

ScarletAmaranth


Size of a pointer should be 8 byte on any 64-bit C/C++ compiler, but the same is not true for the size of int.

Wikipedia has a good explanation on that:

In many programming environments for C and C-derived languages on 64-bit machines, "int" variables are still 32 bits wide, but long integers and pointers are 64 bits wide. These are described as having an LP64 data model. Another alternative is the ILP64 data model in which all three data types are 64 bits wide, and even SILP64 where "short" integers are also 64 bits wide.[citation needed] However, in most cases the modifications required are relatively minor and straightforward, and many well-written programs can simply be recompiled for the new environment without changes. Another alternative is the LLP64 model, which maintains compatibility with 32-bit code by leaving both int and long as 32-bit. "LL" refers to the "long long integer" type, which is at least 64 bits on all platforms, including 32-bit environments.

like image 28
Rahul Tripathi Avatar answered Sep 24 '22 19:09

Rahul Tripathi