386 views
7 7 votes

What is the output of the following code?

#include <stdio.h>

struct Student {
    int roll;
    int marks;
};

int main() {
    struct Student s[3] = {
        {1, 50},
        {2, 60},
        {3, 70}
    };

    struct Student *p = s;

    (p + 1)->marks = (p + 1)->marks + 5;
    p++;
    p->roll = (p - 1)->roll + p->roll;

    printf("%d %d %d", s[0].roll, s[1].roll, s[1].marks);

    return 0;
}
  1. $\texttt{1 2 65}$
     
  2. $\texttt{1 3 65}$
     
  3. $\texttt{2 3 65}$
     
  4. $\texttt{1 3 60}$

3 Answers

0 0 votes

Here, $\texttt{s}$ is an array of structures.

Initially:

$\texttt{s[0].roll = 1}$, $\texttt{s[0].marks = 50}$

$\texttt{s[1].roll = 2}$, $\texttt{s[1].marks = 60}$

$\texttt{s[2].roll = 3}$, $\texttt{s[2].marks = 70}$

Now:

$\texttt{struct Student *p = s;}$

So, $\texttt{p}$ points to $\texttt{s[0]}$.

First statement:

$\texttt{(p + 1)->marks = (p + 1)->marks + 5;}$

Here, $\texttt{p + 1}$ points to $\texttt{s[1]}$.

So,

$\texttt{s[1].marks = 60 + 5 = 65}$

Next:

$\texttt{p++;}$

Now, $\texttt{p}$ points to $\texttt{s[1]}$.

Next:

$\texttt{p->roll = (p - 1)->roll + p->roll;}$

Here, $\texttt{p->roll}$ means $\texttt{s[1].roll}$.

Also, $\texttt{(p - 1)->roll}$ means $\texttt{s[0].roll}$.

So,

$\texttt{s[1].roll = 1 + 2 = 3}$

Therefore:

$\texttt{s[0].roll = 1}$

$\texttt{s[1].roll = 3}$

$\texttt{s[1].marks = 65}$

So the output is:

$\texttt{1 3 65}$
 

Answer: B

Answer:
Position:
Show:

Related questions

6 6 votes
2 2 answers
329
329 views
GO Classes asked Jun 30
329 views
What will happen when the following code is compiled?#include <stdio.h struct Node { int data; }; int main() { struct Node n = {25}; struct Node *p = &n; printf("%d", *p....
5 5 votes
1 1 answer
320
320 views
GO Classes asked Jun 30
320 views
Assume:$\texttt{char}$ takes $1$ byte $\texttt{int}$ takes $4$ bytes $\texttt{int}$ must be stored at an address divisible by $4$ Structure size is rounded to a multiple ...
5 5 votes
2 2 answers
327
327 views
GO Classes asked Jun 30
327 views
What is the output of the following code?#include <stdio.h struct Book { char name[4]; int pages; }; int main() { struct Book b1 = {"CAT", 50}; struct Book b2; b2 = b1; b...
5 5 votes
2 2 answers
320
320 views
GO Classes asked Jun 30
320 views
What is the output of the following code?#include <stdio.h struct Item { int code; int price; }; void f(struct Item x) { x.code = x.code + 1; x.price = x.price + 50; } vo...