323 views
6 6 votes

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.data);

    return 0;
}
  1. $\texttt{25}$
     
  2. Address of $\texttt{data}$
     
  3. Compilation error
     
  4. Undefined behavior

2 Answers

1 1 vote

Here, $\texttt{p}$ is a pointer to a structure.

To access the member using a structure pointer, we should write:

$\texttt{p->data}$

or

$\texttt{(*p).data}$

But the code uses:

$\texttt{*p.data}$

The dot operator $\texttt{.}$ has higher precedence than the dereference operator $\texttt{*}$.

So, this expression is treated as:

$\texttt{*(p.data)}$

But $\texttt{p}$ is a pointer, not a structure variable.

So, $\texttt{p.data}$ is invalid.

Therefore, the code gives a compilation error.


Answer: C

Answer:
Position:
Show:

Related questions

7 7 votes
3 3 answers
377
377 views
GO Classes asked Jun 30
377 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, 50}, {2, 60}, {3, 70} }; stru...
5 5 votes
1 1 answer
312
312 views
GO Classes asked Jun 30
312 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
318
318 views
GO Classes asked Jun 30
318 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
309
309 views
GO Classes asked Jun 30
309 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...