Aeron Akash
Aeron Akash

Reputation: 43

C++ different outputs

The sizeof() function should return the number of bytes of the argument passed to it. How there are different outputs for the sizeof() function while the arguments are essentially same?

#include <iostream>
using namespace std;
int main( )
{
    int b[3][2];
    cout<<sizeof(b)<<endl;
    cout<<sizeof(b+0)<<endl;
    cout<<sizeof(*(b+0))<<endl;
    // the next line prints 0012FF68
    cout<<"The address of b is: "<<b<<endl;
    cout<<"The address of b+1 is: "<<b+1<<endl;
    cout<<"The address of &b is: "<<&b<<endl;
    cout<<"The address of &b+1 is: "<<&b+1<<endl<<endl;
    return 0;
}

Upvotes: 3

Views: 88

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

sizeof(b)

This is the size of the entire b object, in bytes. b is an array of ints, a 3x2 array, so this is sizeof(int)*3*2.

sizeof(b+0)

When used in an expression, an array object decays to a pointer to the first value in the array. That is: any expression. Adding 0 to something is an expression. This is sizeof(int (*)[2]).

sizeof(*(b+0))

The array contains an array ints. Dereferencing a pointer to the first value of this array, or any other value in the array, gives an int. This is sizeof(int[2]).

And that's why all of these are different. "Essentially same" is not good enough, when C++ is concerned. C++ has no room for error, zero tolerance. If something is not exactly the same, then it is not the same. The End.

Upvotes: 8

Related Questions