×

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 2

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

Program 1:

#include <iostream>
using namespace std;

int main()
{
    typedef struct
    {
        int A;
        char* STR;
    } S;

    S ob = { 10, "india" };

    S* ptr;
    ptr = &ob;

    cout << ptr->A << " " << ptr->STR[2];

    return 0;
}

Output:

10 d

Explanation:

Here, we created a local structure with two members A and STR that is defined in the main() function. and created the object that is ob, and a pointer ptr, assigned the address of ob to ptr.

cout <<ptr->A<<" "<<ptr->STR[2];

Here, we accessed elements using referential operator "->".

ptr->A will be "10" and ptr->STR[2] will "d", it will access the 2nd element of the string STR.

Program 2:

#include <iostream>
using namespace std;

typedef struct{
    int A;
    char* STR;
} S;

int main()
{
    S ob = { 10, "india" };

    cout << sizeof(ob);

    return 0;
}

Output:

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

Explanation:

Here, we created a structure with two members, one is an integer variable and another is a character pointer. We know that size of an integer is 4 bytes / 8 bytes and the size of any type of pointer is also 4 bytes / 8 bytes.

Program 3:

#include <iostream>
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: 12
In a 64-bit system: 24

Explanation:

Here, A and B will allocate two blocks of 4 bytes / 8 bytes, and normally character variable takes 1-byte memory space but due to structure padding c1 and c2 will take 1-1 byte and block is padded by remaining 2 bytes / 6 bytes. And then no other variable can use the padded space.

1st block will store A, 2nd block will store B, and 3rd block will store c1, c2, and 2 bytes / 6 bytes space padding. 

Then the final size of the structure will be 12 / 24 bytes.





Comments and Discussions!

Load comments ↻





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