![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Sep 2005
Posts: 33
Rep Power: 0
![]() |
sizeof struct and class
From what i know,In C the sizeof a structure or the obj of that structure is same as the same of the size of sum of all the data members of the structure..
I have worked it on AIX Unix using a Visual Age compiler and noticed that it works that way,i think similar holds good for C++ class as well unless the class is empty(empty class always shows sizeof as 1,while a program with empty structure doent even pass compilation....wonder why both these results??) however i get different results if i compile it on Microsoft Visual C++,the size obtained is much more...here are the codes are tried out... class foo
{
private:
int a;
char b;
int c;
}obj1;
void main()
{
cout<<"sizeof int ["<<sizeof(int)<<"]"<<endl;
cout<<"sizeof char ["<<sizeof(char)<<"]"<<endl;
cout<<"expected sizeof class ["<<sizeof(int)+sizeof(int)+sizeof(char)<<"]"<<endl;
cout<<"sizeof class ["<<sizeof(foo)<<"]"<<endl;
cout<<"sizeof obj ["<<sizeof(obj1)<<"]"<<endl;
}sizeof int [4] sizeof char [1] expected sizeof class [9] sizeof class [12] sizeof obj [12] code for c: struct foo
{
int a;
char b;
int c;
}obj1;
void main()
{
printf("sizeof int [%d]\n",sizeof(int));
printf("sizeof int [%d]\n",sizeof(char));
printf("expected sizeof structure[%d]\n",sizeof(int)+sizeof(int)+sizeof(char));
printf("sizeof structure [%d]\n",sizeof(struct foo));
printf("sizeof int [%d]\n",sizeof(obj1));
}output: sizeof int [4] sizeof int [1] expected sizeof structure[9] sizeof structure [12] sizeof int [12] can anyone explain why this occurs,this is got to do with some padding concept,is it? what is this padding concept?also please try to anser about the empty class and struct... P.S: too many questions in this post,may be silly too but im learning in to it and with ur replies hopefully i will be able to learn faster... |
|
|
|
|
|
#2 | |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
It has everything to do with padding and alignment. Often, you may specify to what degree that takes place.
Quote:
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|