Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ address value and sizeof

Tags:

c++

c

sizeof

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

like image 472
green2rabbit Avatar asked Dec 01 '25 23:12

green2rabbit


2 Answers

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)
like image 75
Tim Avatar answered Dec 04 '25 12:12

Tim


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

like image 38
caustik Avatar answered Dec 04 '25 13:12

caustik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!