yogi
yogi

Reputation: 231

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

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.

Upvotes: 6

Views: 14021

Answers (4)

gliderkite
gliderkite

Reputation: 8928

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.

Upvotes: 10

user195488
user195488

Reputation:

For 32-bit systems, the 'de facto' standard is ILP32 - that is, int, long and pointer are all 32-bit quantities.

For 64-bit systems, the primary Unix 'de facto' standard is LP64 - long and pointer are 64-bit (but int is 32-bit). The Windows 64-bit standard is LLP64 - long long and pointer are 64-bit (but long and int are both 32-bit).

At one time, some Unix systems used an ILP64 organization.

None of these de facto standards is legislated by the C standard (ISO/IEC 9899:1999), but all are permitted by it.

and

If you are concerned with portability, or you want the name of the type reflects the size, you can look at the header , where the following macros are available:

int8_t int16_t int32_t int64_t

int8_t is guaranteed to be 8 bits, and int16_t is guaranteed to be 16 bits, etc.

See this question.

Upvotes: 2

Mark B
Mark B

Reputation: 96233

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.

Upvotes: 5

templatetypedef
templatetypedef

Reputation: 372664

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!

Upvotes: 19

Related Questions