Q:

C++ Structures | Find output programs | Set 2

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ Structures (set 2).

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

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

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

All Answers

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

Answer Program 1:

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.

Answer Program 2:

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.

Answer Program 3:

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.

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 3... >>
<< C++ Structures | Find output programs | Set 1...