sizeof(var) & sizeof(&var)

Discussion in 'C++' started by shikharhis, Mar 29, 2009.

  1. shikharhis

    shikharhis New Member

    Joined:
    Mar 22, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hello I need help with this program 's output.

    #include <iostream>
    #include <string>
    using namespace std;
    int main(){
    char name='a';
    int anint=10;
    double afloat=1.2;
    cout << name << " , size of var is : " << sizeof(name) << " , size of ptr is : " << sizeof(&name)<< endl;
    cout << anint << " , size of var is : " << sizeof(anint) << " , size of ptr is : " << sizeof(&anint)<< endl;
    cout << afloat << " , size of var is : " << sizeof(afloat) << " , size of ptr is : " << sizeof(&afloat)<< endl;
    return 0;
    }
    • Are “size of var” and “size of ptr” same for a datatype?
    • Are “size of var” same for all the datatypes?
    • Are “size of ptr” same for all the datatypes?
    In all the above cases, explain and justify your answer.



    I feel
    1.
    No the size of var and size of ptr is not same for all the datatypes.
    This is because the size of var is the characterstic of the data type whereas the ptr stores the add in an float. So the size of ptr is outputted as 4 in all the 3 cases.

    2.
    No, the size of var is characterstic of the data type, and since the data types are different so the sizes are also different.

    3.
    Yes the size of ptr is same for all the variables. The ptr stores the add in an float, So the size of ptr is outputted as 4 in all the 3 cases.



    Am I right??? Please help.
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    1. sizeof var and sizeof &var will not necessarily be the same for a datatype. If the datatype size is the same size as a pointer (e.g. if ints are 4 bytes and pointers are 4 bytes) then sizeof(int)==sizeof(int*).

    I don't know where you got "the ptr stores the add in an float" - pointers are stored in pointer types, which could be considered a special kind of integer, but they're definitely not stored in floats.

    2. seems OK

    3. Correct, except for the "pointer storing the address in a float" nonsense.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice