×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

C++ Structures | Find output programs | Set 3

This section contains the C++ find output programs with their explanations on C++ Structures (set 3).
Submitted by Nidhi, on June 17, 2020

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

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".

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

Output:

In a 32-bit system: 4
In a 64-bit system: 8

Explanation:

We compiled this program on a 32-bit system.

Here, we created a structure with 4 members, and a pointer to the structure.

cout<<sizeof(ptr);

The above statement will print "4". Because, the size of any type of pointer in a 32-bit system is 4 bytes.

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

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.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.