289 views
7 7 votes

What is the output of the following code?

#include <stdio.h>

struct Item {
    int code;
    int price;
};

void update(struct Item *p) {
    p->price = p->price + 20;
    (*p).code = (*p).code + 1;
}

int main() {
    struct Item i1 = {10, 100};

    update(&i1);

    printf("%d %d", i1.code, i1.price);

    return 0;
}
  1. $\texttt{10 100}$
     
  2. $\texttt{11 120}$
     
  3. $\texttt{10 120}$
     
  4. Compilation error

2 Answers

0 0 votes

Here, $\texttt{i1}$ is a structure variable.

The function call is:

$\texttt{update(\&i1);}$

So, the address of $\texttt{i1}$ is passed to the function.

Inside the function, $\texttt{p}$ points to the original structure variable $\texttt{i1}$.


First statement:

$\texttt{p->price = p->price + 20;}$

So,

$\texttt{i1.price = 100 + 20 = 120}$


Second statement:

$\texttt{(*p).code = (*p).code + 1;}$

Here, $\texttt{(*p).code}$ is the same as $\texttt{p->code}$.

So,

$\texttt{i1.code = 10 + 1 = 11}$


Therefore, the output is:

$\texttt{11 120}$
 

Answer: B

Answer:
Position:
Show:

Related questions

6 6 votes
2 2 answers
259
259 views
GO Classes asked Jun 29
259 views
What is the output of the following code?#include <stdio.h struct Box { int width; int height; }; int main() { struct Box b = {4, 6}; struct Box *p = &b; p->width = p->wi...
6 6 votes
3 3 answers
308
308 views
GO Classes asked Jun 29
308 views
What will happen when the following code is compiled?#include <stdio.h struct Point { int x; int y; }; int main() { struct Point p1 = {2, 4}; struct Point p2; p2 = p1; p2...
6 6 votes
2 2 answers
281
281 views
GO Classes asked Jun 29
281 views
What is the output of the following code?#include <stdio.h struct Book { char name; float price; int pages; }; int main() { struct Book b1 = {'C', 150.5, 300}; b1.pages =...
5 5 votes
2 2 answers
301
301 views
GO Classes asked Jun 29
301 views
What is the output of the following code?#include <stdio.h struct Student { int roll; int marks; }; int main() { struct Student s[3] = { {1, 70}, {2, 80}, {3, 90} }; s .m...