C++ address value and sizeof

682 views Asked by At

On my computer. When I test the code:

int main()
{
    int i=123;
    return 0;
}

using

g++ -g test.cpp -o test

I found when I enter:

print &i            output: 0x7fffffffe18c
print sizeof(&i)    output: 8

I was confused, the address of i is 6 byte, why sizeof(&i)==8? Thanks a lot

3

There are 3 answers

1
Tim On BEST ANSWER

When you do this, you are getting the address of i

print &i            output: 0x7fffffffe18c

The output show the address number that the variable i is stored, but printf will remove the leading zero, so you could only see 0x7fffffffe18c instead of 0x00007fffffffe18c, you could use a debugger to verify it

When you call sizeof(&i)

print sizeof(&i)    output: 8

You getting 8 bytes, because you are getting the sizeof the address and not the variable i size, if you want to get the variable size just do

sizeof(i)
0
kfsone On

sizeof works with types, not values, because values must ultimately be stored in a container of some type, and the compiler usually can't predict what value a variable is going to have to hold at compile time:

void f(int* ptr);  // does it need to hold 0? 1000? 1<<27?

When you write

sizeof(i);
size_t f(int* ptr) { return sizeof(ptr); }

is actually treated as equivalent to

sizeof decltype(i);
size_t f(int* ptr) { return sizeof(decltype(ptr)); }

where decltype(i) evaluates to whatever type i was declared as:

int i; :- decltype(i) evaluates to "int"
int* i; :- decltype(i) evaluates to "int*"
int*& i; :- decltype(i) evaluates to "int*&"

and in f

sizeof(ptr) :- decltype(ptr) evaluates to "int*"

You compiled a 64-bit executable so pointers have to be able to hold values [0,1^64), which requires 64-bits or 8 bytes.

#include <cstdio>

int main()
{
    int i = 10;
    printf("i = %d, &i = %0p, sizeof(&i) = %d\n", i, &i, sizeof(&i));
}

On a 32-bit machine: http://ideone.com/htfy9R

0
caustik On

The address is actually 0x00007fffffffe18c, print doesn't display the leading zeros.