sizeof(var) & sizeof(&var)

shikharhis's Avatar
Newbie Member
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.
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.