C++ Structures | Find output programs | Set 5

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

Program 1:

#include <iostream>
using namespace std;

struct st1 {
    int A = 10;

    struct st2 {
        char ch = 'A';
    } S;
} SS;

int main()
{
    struct st1* PTR;

    int X = 0;

    X = PTR->A + PTR->S.ch;

    cout << X;

    return 0;
}

Output:

Segmentation fault
or
Garbage value

Explanation:

This program will print either garbage value or a segmentation fault. Because here we created a pointer PTR but did not assign any address to it, so that pointer will point to the unknown or garbage location that's why it will calculate and print either garbage value or a segmentation fault.

Program 2:

#include <iostream>
using namespace std;

struct st1 {
    int A = 10;

    struct st2 {
        char ch = 'A';
    } S;

} SS;

int main()
{
    struct st1* PTR = &SS;

    int X = 0;

    X = PTR->A + PTR->S.ch;

    cout << X;

    return 0;
}

Output:

75

Explanation:

Here, we declared a structure within a structure, and a pointer in the main() function.

struct st1 *PTR = &SS;

The pointer PTR is pointing to the outermost structure. Evaluate the expression,

X = PTR->A + PTR->S.ch;
X = 10 + 'A';
X = 10 + 65; //ASCII value of 'A' is 65.
X = 75;

The final value of X is 75 will be printed on the console screen.

Program 3:

#include <iostream>
using namespace std;

struct st1 {
    int A = 10;

    struct st2 {
        char ch = 'A';
    } S;

} SS;

void fun(struct st1* PTR)
{
    int X = 0;

    X = PTR->A + PTR->S.ch;

    cout << X;
}

int main()
{
    fun(&SS);
    return 0;
}

Output:

75

Explanation:

Here, we declared a structure within a structure, and created a function fun() which is accepting the pointer the structure as an argument.

fun(&SS);

In the main() function, we passed the address of structure to the function.

Now, the pointer PTR will point to the outermost structure. Evaluate the expression,

X = PTR->A + PTR->S.ch;
X = 10 + 'A';
X = 10 + 65; //ASCII value of 'A' is 65.
X = 75;

The final value of X is 75 will be printed on the console screen.





Comments and Discussions!

Load comments ↻





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