Q:

C++ Structures | Find output programs | Set 3

belongs to collection: C++ find output programs

0

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;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

Output:

In a 32-bit system: 10
In a 64-bit system: 18

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:

In a 32-bit system: 10
In a 64-bit system: 18

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:

16

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

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Structures | Find output programs | Set 4... >>
<< C++ Structures | Find output programs | Set 2...