Challenge - 5 Problems
Nested Structures Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested struct member access
What is the output of this C code snippet?
C
typedef struct {
int x;
int y;
} Point;
typedef struct {
Point topLeft;
Point bottomRight;
} Rectangle;
#include <stdio.h>
int main() {
Rectangle rect = {{1, 2}, {3, 4}};
printf("%d\n", rect.bottomRight.x);
return 0;
}Attempts:
2 left
💡 Hint
Look at how the nested structs are initialized and accessed.
✗ Incorrect
The Rectangle struct has two Point members: topLeft and bottomRight. The code prints rect.bottomRight.x, which is initialized to 3.
❓ Predict Output
intermediate2:00remaining
Value of nested struct after assignment
What is the value of p2.y after this code runs?
C
typedef struct {
int x;
int y;
} Point;
#include <stdio.h>
int main() {
Point p1 = {5, 10};
Point p2;
p2 = p1;
p2.y = 20;
printf("%d\n", p2.y);
return 0;
}Attempts:
2 left
💡 Hint
Remember that assigning structs copies all members.
✗ Incorrect
p2 is assigned p1, then p2.y is changed to 20, so printing p2.y outputs 20.
❓ Predict Output
advanced2:00remaining
Output of nested struct pointer access
What does this program print?
C
typedef struct {
int id;
struct {
int day;
int month;
int year;
} date;
} Event;
#include <stdio.h>
int main() {
Event e = {101, {15, 8, 2023}};
Event *ptr = &e;
printf("%d-%d-%d\n", ptr->date.day, ptr->date.month, ptr->date.year);
return 0;
}Attempts:
2 left
💡 Hint
Use the arrow operator to access nested struct members through a pointer.
✗ Incorrect
The pointer ptr points to e. Accessing ptr->date.day etc. prints the date in day-month-year order.
❓ Predict Output
advanced2:00remaining
Result of modifying nested struct via pointer
What is the output of this program?
C
typedef struct {
int x;
int y;
} Point;
typedef struct {
Point center;
int radius;
} Circle;
#include <stdio.h>
int main() {
Circle c = {{0, 0}, 5};
Circle *pc = &c;
pc->center.x = 10;
printf("%d\n", c.center.x);
return 0;
}Attempts:
2 left
💡 Hint
Changing a nested struct member via pointer affects the original struct.
✗ Incorrect
The pointer pc points to c. Changing pc->center.x changes c.center.x to 10.
❓ Predict Output
expert3:00remaining
Output of complex nested struct initialization and access
What is the output of this program?
C
typedef struct {
int day;
int month;
int year;
} Date;
typedef struct {
char name[20];
Date birthdate;
} Person;
#include <stdio.h>
int main() {
Person people[2] = {
{"Alice", {1, 1, 2000}},
{"Bob", {31, 12, 1999}}
};
printf("%s was born on %d/%d/%d\n", people[1].name, people[1].birthdate.day, people[1].birthdate.month, people[1].birthdate.year);
return 0;
}Attempts:
2 left
💡 Hint
Check the array index and nested struct initialization carefully.
✗ Incorrect
people[1] refers to the second element, Bob, with birthdate 31/12/1999.