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:
View worked solution
Answer: A
Let's analyze the memory layout and pointer arithmetic step-by-step:
- Structure Definition & Memory Layout:
The structure
Ournodeis defined as:struct Ournode { char x, y, z; };Since each member is of type
char(1 byte), they are stored contiguously in memory with no padding. The offsets from the base address of the structure are:xis at offset 0yis at offset 1zis at offset 2
- Initialization:
The variable
pis initialized as:struct Ournode p = {'1', '0', 'a' + 2};p.x = '1'p.y = '0'p.z = 'a' + 2, which evaluates to the character'c'(since the ASCII value of'a'is 97, 97 + 2 = 99, which is the ASCII value of'c').
- Pointer Arithmetic:
qis a pointer pointing top. When we cast it to(char*)q, pointer arithmetic is performed in steps of 1 byte (the size ofchar):*((char*)q + 1)accesses the byte at offset 1, which corresponds top.y. Its value is'0'.*((char*)q + 2)accesses the byte at offset 2, which corresponds top.z. Its value is'c'.
- Output:
The
printfstatement prints these characters using the%cformat specifier:printf("%c, %c", '0', 'c');This outputs:
0, c
Therefore, the correct option is A.
Free practice · Your answers on this page are not saved.
