This section contains the C++ find output programs with their explanations on C++ Structures (set 3).
Program 1:
#include <iostream>
#pragma pack(1)
using namespace std;
typedef struct{
int A;
int B;
char c1;
char c2;
} S;
int main()
{
cout << sizeof(S);
return 0;
}
Program 2:
#include <iostream>
using namespace std;
struct st {
char c1;
int A;
int B;
char c2;
};
int main()
{
struct st* ptr;
cout << sizeof(ptr);
return 0;
}
Program 3:
#include <iostream>
using namespace std;
struct st {
char c1;
int A;
int B;
char c2;
};
int main()
{
struct st ob;
struct st* ptr = &ob;
cout << sizeof(*ptr);
return 0;
}
Answer Program 1:
Output:
Explanation:
We compiled the program on a 32-bit system. It will print "10" on the console screen.
Normally, the above program will print "12" due to structure padding. But, here, we used #pragma pack(1) directives. It is used to avoid the structure padding. Then the size of the above structure will be "10".
Answer Program 2:
Output:
Explanation:
We compiled the program on a 32-bit system. It will print "10" on the console screen.
Normally, the above program will print "12" due to structure padding. But, here, we used #pragma pack(1) directives. It is used to avoid the structure padding. Then the size of the above structure will be "10".
Answer Program 3:
Output:
Explanation:
We compiled the program on 32-bit based system.
Here, we created a structure, C++ uses structure padding and allocate space for variables block-wise, block size is 4 bytes for 32-bit based system.
In the main() function we created a structure variable ob, and a pointer ptr that contains the address of ob.
cout<<sizeof(*ptr);
The above statement will print the size of the structure.
1st block is allocated for c1 that is 4 bytes. 2nd block is allocated for A that is 4 bytes. 3rd block is allocated for B that is 4 bytes. 4th block is allocated for c2 that is 4 bytes.
Then, the total size is "16" bytes will be printed on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer