Bird
Raised Fist0
Cprogramming~20 mins

Structure vs union comparison - Practice Questions

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Structure vs Union Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of structure size and member values
What is the output of this C program?
C
#include <stdio.h>

struct Data {
    int i;
    char c;
    double d;
};

int main() {
    struct Data s = {5, 'A', 3.14};
    printf("%d %c %.2f\n", s.i, s.c, s.d);
    printf("Size of struct Data: %zu\n", sizeof(s));
    return 0;
}
A
5 A 3.14
Size of struct Data: 12
B
5 A 3.14
Size of struct Data: 24
C
5 A 3.14
Size of struct Data: 16
D
5 A 3.14
Size of struct Data: 13
Attempts:
2 left
💡 Hint
Think about padding and alignment in structures.
❓ Predict Output
intermediate
2:00remaining
Output of union member assignment
What will be printed by this C program?
C
#include <stdio.h>

union Value {
    int i;
    float f;
};

int main() {
    union Value v;
    v.i = 1065353216;
    printf("%d %.2f\n", v.i, v.f);
    return 0;
}
A1065353216 1.00
B1065353216 0.00
C0 1.00
D1065353216 1065353216.00
Attempts:
2 left
💡 Hint
Remember that union members share the same memory.
🔧 Debug
advanced
2:30remaining
Why does this union code print unexpected values?
Consider this code snippet. Why does printing both union members after assignment give unexpected results?
C
#include <stdio.h>

union Data {
    int i;
    char str[4];
};

int main() {
    union Data d;
    d.i = 0x41424344;
    printf("%d %c %c %c %c\n", d.i, d.str[0], d.str[1], d.str[2], d.str[3]);
    return 0;
}
ABecause the char array is not initialized, it contains garbage values unrelated to the int.
BBecause the union stores all members in the same memory, the char array shows the byte representation of the int, which depends on endianness.
CBecause the int and char array have different sizes, accessing str causes a buffer overflow.
DBecause the printf format specifiers are incorrect for union members.
Attempts:
2 left
💡 Hint
Think about how data is stored in memory and how endianness affects byte order.
📝 Syntax
advanced
2:00remaining
Which code snippet correctly declares and initializes a union?
Which of the following code snippets correctly declares a union and initializes its member?
Aunion Number n; n.i = 10; union Number { int i; float f; };
Bunion Number { int i; float f; } n; n = {10};
Cunion Number { int i; float f; } n = (int)10;
Dunion Number { int i; float f; } n = { .i = 10 };
Attempts:
2 left
💡 Hint
Look for correct syntax for union declaration and initialization.
🚀 Application
expert
3:00remaining
Memory size comparison between struct and union
Given the following definitions, what is the total size in bytes of struct S and union U on a typical 64-bit system?
C
struct S {
    char c;
    int i;
    double d;
};

union U {
    char c;
    int i;
    double d;
};
Astruct S: 16 bytes, union U: 8 bytes
Bstruct S: 16 bytes, union U: 24 bytes
Cstruct S: 24 bytes, union U: 8 bytes
Dstruct S: 24 bytes, union U: 24 bytes
Attempts:
2 left
💡 Hint
Remember struct size includes all members plus padding; union size equals largest member size.

Practice

(1/5)
1. What is the main difference between a struct and a union in C?
easy
A. Both struct and union share the same memory for all members.
B. A struct stores all members separately, while a union shares the same memory for all members.
C. Both struct and union store members in separate memory locations.
D. A union stores all members separately, while a struct shares the same memory for all members.

Solution

  1. Step 1: Understand struct memory allocation

    A struct allocates separate memory for each member, so all members exist independently.
  2. Step 2: Understand union memory allocation

    A union uses the same memory location for all members, so only one member can hold a value at a time.
  3. Final Answer:

    A struct stores all members separately, while a union shares the same memory for all members. -> Option B
  4. Quick Check:

    Struct = separate memory, Union = shared memory [OK]
Hint: Struct = all data stored; Union = one data stored at a time [OK]
Common Mistakes:
  • Thinking union stores all members separately
  • Confusing struct and union memory sharing
  • Assuming both behave the same in memory
2. Which of the following is the correct syntax to define a union named Data with an int and a float member?
easy
A. union Data = { int i; float f; };
B. struct Data { int i; float f; };
C. union Data ( int i; float f; );
D. union Data { int i; float f; };

Solution

  1. Step 1: Recall union syntax

    The correct syntax uses the keyword union, followed by the name and braces containing members separated by semicolons.
  2. Step 2: Check each option

    union Data { int i; float f; }; matches the correct syntax. struct Data { int i; float f; }; uses struct instead of union. union Data ( int i; float f; ); uses parentheses instead of braces. union Data = { int i; float f; }; uses an equals sign incorrectly.
  3. Final Answer:

    union Data { int i; float f; }; -> Option D
  4. Quick Check:

    union syntax = keyword + name + braces + members [OK]
Hint: Use braces {} and keyword union for definition [OK]
Common Mistakes:
  • Using struct keyword instead of union
  • Using parentheses instead of braces
  • Adding equals sign in definition
3. Consider the following code:
union Data {
  int i;
  float f;
};

int main() {
  union Data d;
  d.i = 10;
  d.f = 3.14;
  printf("%d", d.i);
  return 0;
}

What will be the output?
medium
A. Undefined or garbage value
B. 10
C. 3
D. 3.14

Solution

  1. Step 1: Understand union member assignment

    Assigning d.i = 10; stores 10 in the union memory. Then d.f = 3.14; overwrites the same memory with the float value.
  2. Step 2: Check the printf output

    Printing d.i after assigning d.f reads the memory as int, but the memory holds float bits, causing undefined or garbage output.
  3. Final Answer:

    Undefined or garbage value -> Option A
  4. Quick Check:

    Union stores one value; last assignment wins [OK]
Hint: Last union member assigned overwrites memory [OK]
Common Mistakes:
  • Expecting both values to be stored
  • Printing float as int correctly
  • Ignoring memory overwrite in union
4. Identify the error in this code snippet:
struct Point {
  int x;
  int y;
};

union Point {
  int x;
  int y;
};

int main() {
  struct Point p1 = {1, 2};
  union Point p2;
  p2.x = 3;
  p2.y = 4;
  printf("%d %d", p1.x, p1.y);
  printf("%d %d", p2.x, p2.y);
  return 0;
}
medium
A. Cannot define struct and union with the same name in the same scope.
B. Union members cannot be assigned values.
C. Struct members must be initialized separately, not with braces.
D. printf cannot print multiple variables.

Solution

  1. Step 1: Check struct and union naming rules

    In C, struct and union tags share the same namespace. Defining both with the same name Point causes a redefinition error.
  2. Step 2: Verify other statements

    Union members can be assigned values. Struct initialization with braces is valid. printf can print multiple variables with format specifiers.
  3. Final Answer:

    Cannot define struct and union with the same name in the same scope. -> Option A
  4. Quick Check:

    Struct and union tags must have unique names [OK]
Hint: Struct and union names share namespace; avoid duplicates [OK]
Common Mistakes:
  • Thinking union members can't be assigned
  • Believing struct brace initialization is invalid
  • Assuming printf can't print multiple values
5. You want to store either an integer ID or a floating-point score in a variable but never both at the same time to save memory. Which is the best choice and why?
hard
A. Use a struct because it stores both values separately.
B. Use two separate variables to avoid confusion.
C. Use a union because it shares memory and stores only one value at a time.
D. Use an array to store both values.

Solution

  1. Step 1: Analyze memory needs

    Since only one value (ID or score) is needed at a time, saving memory is important.
  2. Step 2: Choose between struct and union

    A struct stores both values separately, using more memory. A union shares memory for all members, storing only one value at a time, saving memory.
  3. Final Answer:

    Use a union because it shares memory and stores only one value at a time. -> Option C
  4. Quick Check:

    One value at a time + memory saving = union [OK]
Hint: Union saves memory when storing one of many values [OK]
Common Mistakes:
  • Choosing struct and wasting memory
  • Using separate variables unnecessarily
  • Using array which doesn't fit this need
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard