Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof(int) different than sizeof(int*)?

Tags:

c++

c

sizeof

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.

like image 717
yogi Avatar asked Jun 11 '12 17:06

yogi


People also ask

Why is sizeof int *) == sizeof char *)?

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.

Why is sizeof int * 8?

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.

Why size of int is 2 or 4 bytes?

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.

Why is int the same size as long int?

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.


3 Answers

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!

like image 131
templatetypedef Avatar answered Oct 04 '22 17:10

templatetypedef


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.


(*) See the comment of James Kanze.
like image 33
gliderkite Avatar answered Oct 04 '22 16:10

gliderkite


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.

like image 45
Mark B Avatar answered Oct 04 '22 16:10

Mark B