Consider the following C program. #include<stdio.h> struct Ournode{ char…
2018
Consider the following C program.
#include<stdio.h>
struct Ournode{
char x,y,z;
};
int main(){
struct Ournode p = {'1', '0', 'a'+2};
struct Ournode *q = &p;
printf ("%c, %c", *((char*)q+1), *((char*)q+2));
return 0;
}
The output of this program is:
- A.
0, c
- B.
0, a+2
- C.
'0', 'a+2'
- D.
'0', 'c'
Attempted by 265 students.
Show answer & explanation
Correct answer: A
Answer: 0, c
Explanation:
The struct has three char fields stored contiguously: x, y, z. The initializer sets x = '1', y = '0', z = 'a' + 2.
The expression 'a' + 2 is evaluated as an integer arithmetic on the character code for 'a' (ASCII 97), producing ASCII 99, which is the character 'c'.
Casting the pointer q to (char*) treats the struct as a sequence of bytes. *((char*)q + 1) accesses the second byte (y) which is '0'; *((char*)q + 2) accesses the third byte (z) which is 'c'.
printf with the %c format prints characters without surrounding quotes, so the output appears exactly as: 0, c
A video solution is available for this question — log in and enroll to watch it.