0
0
C++programming~20 mins

Defining structures in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Structure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of structure member access
What is the output of this C++ code?
C++
struct Point {
    int x;
    int y;
};

int main() {
    Point p = {3, 4};
    std::cout << p.x + p.y << std::endl;
    return 0;
}
A7
B34
C0
DCompilation error
Attempts:
2 left
💡 Hint
Add the values of x and y members of the structure.
Predict Output
intermediate
2:00remaining
Size of structure with padding
What is the size of this structure on a typical 64-bit system?
C++
struct Data {
    char a;
    int b;
    char c;
};

int main() {
    std::cout << sizeof(Data) << std::endl;
    return 0;
}
A8
B6
C12
D16
Attempts:
2 left
💡 Hint
Consider padding added for alignment between members.
🔧 Debug
advanced
2:00remaining
Identify the error in structure initialization
What error will this code produce?
C++
#include <iostream>
#include <string>

struct Person {
    std::string name;
    int age;
};

int main() {
    Person p = {"Alice"};
    std::cout << p.name << " " << p.age << std::endl;
    return 0;
}
ACompilation error: missing initializer for 'age'
BRuntime error: uninitialized age
COutput: Alice 0
DOutput: Alice garbage_value
Attempts:
2 left
💡 Hint
All members must be initialized or have default values.
🧠 Conceptual
advanced
2:00remaining
Effect of 'typedef' with structures
What does the following code do?
C++
#include <iostream>

typedef struct {
    int id;
    float score;
} Record;

int main() {
    Record r = {101, 95.5};
    std::cout << r.id << " " << r.score << std::endl;
    return 0;
}
ADefines a structure named 'Record' and a variable of that type
BDefines a structure and creates an alias 'Record' for it
CCauses a syntax error due to missing structure name
DDefines a class named 'Record' instead of a structure
Attempts:
2 left
💡 Hint
typedef creates a new name for the unnamed structure.
Predict Output
expert
2:00remaining
Output of nested structure member access
What is the output of this code?
C++
struct Engine {
    int horsepower;
};

struct Car {
    Engine engine;
    int year;
};

int main() {
    Car c = {{250}, 2020};
    std::cout << c.engine.horsepower << " " << c.year << std::endl;
    return 0;
}
A250 0
BCompilation error
C0 2020
D250 2020
Attempts:
2 left
💡 Hint
Nested structures can be initialized with nested braces.