Structure Pitfalls Quiz Interview- C Programming For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Structure and Union

Structure Pitfalls Quiz Interview

Trace the answer-key traps with real compiler output, then test yourself with a quiz and interview questions.

Structure Pitfalls Every C Learner Hits

This is the closing lecture of the structure and union chapter in our free C programming course. The answer key at the end of the chapter lists a handful of programs that either refuse to compile or print something surprising: comparing two structures with ==, using a structure type outside the function that defined it, reading the wrong member of a union, adding up structure sizes by hand, and misusing typedef. Instead of repeating those answers, this lecture reproduces each trap with a fresh program, shows the real compiler message or output, and explains the rule behind it. These are the same traps that cause bugs in embedded C programming when structures describe hardware registers and protocol frames.

At the end you will find a self-check quiz and a set of interview questions, written in plain HTML so you can copy them into any page. The whole free C tutorial series on structures finishes here, so it is a good moment to review.

What You Will Learn

  • Why the C language does not allow == on structures and how to compare them correctly
  • How padding bytes appear and why sizeof is larger than the sum of the members
  • Why a structure defined inside main() is invisible to other functions
  • How a union shares storage and what reading the inactive member really gives you
  • Why unsigned cannot be glued to a typedef name
  • Why a self-referencing typedef needs a structure tag

Prerequisites

All earlier lectures of the structure chapter in the free embedded C course: declaring structures, unions, nested structures, typedef and linked lists. A GCC or Clang compiler makes it easy to reproduce the messages shown here.

Pitfall 1: Comparing Structures with ==

Assignment between two structures of the same type is allowed, and copies every member. Comparison is not. The compiler refuses because there is no sensible built-in meaning: do two structures match when all bytes match, or when all members match? Those are different questions, because of padding.

#include <stdio.h>

struct sample {
    char kind;
    int  value;
};

int main(void)
{
    struct sample x = {'T', 42};
    struct sample y = {'T', 42};

    if (x == y) {
        puts("equal");
    }
    return 0;
}

Compiling this with gcc -std=c11 -fsyntax-only ep_cmp_bad.c gives an error like the following (wording differs a little between compiler versions).

ep_cmp_bad.c: In function 'main':
ep_cmp_bad.c:13:11: error: invalid operands to binary == (have 'struct sample' and 'struct sample')
   13 |     if (x == y) {
      |           ^~

The correct approach is a function that compares the members you care about, one by one. The working program below also prints the layout, which brings us to padding.

#include <stdio.h>
#include <stddef.h>

struct sample {
    char kind;
    int  value;
};

/* The only portable way to compare structures: compare member by member. */
static int same_sample(const struct sample *a, const struct sample *b)
{
    return a->kind == b->kind && a->value == b->value;
}

int main(void)
{
    struct sample x = {'T', 42};
    struct sample y = {'T', 42};

    printf("same_sample      : %d\n", same_sample(&x, &y));
    printf("sizeof(sample)   : %zu\n", sizeof(struct sample));
    printf("offset of kind   : %zu\n", offsetof(struct sample, kind));
    printf("offset of value  : %zu\n", offsetof(struct sample, value));
    return 0;
}
same_sample      : 1
sizeof(sample)   : 8
offset of kind   : 0
offset of value  : 4
Layout of struct sample: why sizeof is 8, not 5
byte 0kindbytes 1-3paddingbytes 4-7value

The compiler placed value at offset 4 so that the integer sits on a four-byte boundary, which most processors need or prefer. The three unused bytes are padding and their contents are not defined. That is exactly why memcmp() on two structures is unreliable: two structures with equal members can differ in their padding bytes.

Rule:

Compare structures member by member. Use memcmp() only on structures you have fully cleared with memset() first, and only when you are sure there is no padding surprise.

Pitfall 2: A Structure Declared Inside main()

A structure type follows the same scope rules as a variable. If you declare struct point inside main(), only code inside that block can see it. A helper function written above or below cannot, even though the name looks identical.

#include <stdio.h>

static void show(struct point *p)
{
    printf("%d\n", p->x);
}

int main(void)
{
    struct point {
        int x;
    } pt = {3};

    show(&pt);
    return 0;
}
ep_scope_bad.c:3:25: warning: 'struct point' declared inside parameter list will not be visible outside of this definition or declaration
    3 | static void show(struct point *p)
      |                         ^~~~~
ep_scope_bad.c: In function 'show':
ep_scope_bad.c:5:21: error: invalid use of undefined type 'struct point'
    5 |     printf("%d\n", p->x);
      |                     ^~

GCC first warns that struct point was declared inside a parameter list, which means it is a brand new, unrelated type, and then fails when the function tries to use p->x. The fix is to move the definition to file scope, above every function that uses it, or into a header file shared by several source files. In embedded projects, structure definitions that describe a peripheral or a message always live in headers.

Pitfall 3: Reading the Wrong Union Member

A union gives all its members the same starting address, so the storage is as large as the biggest member. Only the member written last holds a meaningful value for that member’s type. Reading another member reinterprets the same bytes. The program below stores the float 1.0 and then looks at the same four bytes as an integer and as four separate bytes.

#include <stdio.h>
#include <stdint.h>

union view {
    float         f;
    uint32_t      bits;
    unsigned char byte[4];
};

int main(void)
{
    union view v;

    v.f = 1.0f;                         /* last member written: f */
    printf("sizeof(union)  : %zu\n", sizeof v);
    printf("bits as hex    : 0x%08X\n", (unsigned)v.bits);
    printf("bytes in memory:");
    for (int i = 0; i < 4; i++) {
        printf(" %02X", v.byte[i]);
    }
    putchar('\n');

    v.bits = 0x40490FDBu;               /* now bits is the active member */
    printf("same storage as float: %.5f\n", v.f);
    return 0;
}
sizeof(union)  : 4
bits as hex    : 0x3F800000
bytes in memory: 00 00 80 3F
same storage as float: 3.14159
One storage area, three views
union viewf: floatbits: uint32_tbyte[4]
all three start at the same address and the union is 4 bytes in total

Reading bits after writing f shows the IEEE-754 pattern of 1.0, which is 0x3F800000. The byte view prints the same value backwards, 00 00 80 3F, because the machine is little-endian: the least significant byte is stored first. On a big-endian machine the bytes would appear in the opposite order, so any code that depends on the byte order of a union must be written with that in mind.

Note:

C11 allows reading a different union member and treats the bytes as the new type, but the resulting value is implementation-defined, and C++ forbids it. For portable code prefer memcpy() between objects, and use unions mainly when you alternate meaning deliberately, such as a protocol payload with a type tag.

Pitfall 4: Adding Member Sizes by Hand

The chapter answer key computes the size of a nested structure by adding the member sizes. That works only if the compiler adds no padding, which is not true on modern systems. Use sizeof and offsetof from stddef.h to ask the compiler instead of guessing.

#include <stdio.h>
#include <stddef.h>

struct inner {
    char tag[15];
    int  id;
};

union payload {
    char         text[15];
    struct inner in;
};

struct outer {
    char          label[20];
    short         flag;
    union payload p;
};

int main(void)
{
    printf("sizeof(struct inner)  : %zu\n", sizeof(struct inner));
    printf("  offset of id        : %zu\n", offsetof(struct inner, id));
    printf("sizeof(union payload) : %zu\n", sizeof(union payload));
    printf("sizeof(struct outer)  : %zu\n", sizeof(struct outer));
    printf("  offset of flag      : %zu\n", offsetof(struct outer, flag));
    printf("  offset of p         : %zu\n", offsetof(struct outer, p));
    return 0;
}
sizeof(struct inner)  : 20
  offset of id        : 16
sizeof(union payload) : 20
sizeof(struct outer)  : 44
  offset of flag      : 20
  offset of p         : 24
struct outer: where each member lands
0-19label[20]20-21flag22-23padding24-43union payload (20 bytes)

Walk through the result. The inner structure has a 15-byte array and an integer; the integer needs alignment 4, so one padding byte follows the array and the structure is 20 bytes. The union takes the size of its largest member, 20 bytes, and the alignment of its strictest member, 4. In the outer structure the short integer lands at offset 20, then two padding bytes bring the offset to 24 so that the union is aligned, and the total is 44. Adding the member sizes by hand gives 20 + 2 + 20 = 42, which misses the two padding bytes and is wrong; the real size is 44.

TechniqueEffectCost
Reorder members, largest alignment firstOften removes paddingNone
__attribute__((packed)) (GCC/Clang)Removes all paddingSlower or faulting unaligned access on some CPUs
Explicit uint8_t reserved fieldsMakes layout visible in the sourceSlightly longer definition

Pitfall 5: typedef Surprises

A typedef creates a new name for a complete type. You cannot modify that name with unsigned, long or short afterwards, because those words are type specifiers that combine only with the basic type keywords. Second, a structure that points to itself cannot use its own typedef name inside its body, because the name does not exist until the declaration ends.

#include <stdio.h>

typedef int counter_t;

typedef struct {
    int      value;
    NodeT   *next;
} NodeT;

int main(void)
{
    unsigned counter_t n = 5;
    printf("%u\n", n);
    return 0;
}
ep_typedef_bad.c:7:5: error: unknown type name 'NodeT'
    7 |     NodeT   *next;
      |     ^~~~~
ep_typedef_bad.c: In function 'main':
ep_typedef_bad.c:12:24: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'n'
   12 |     unsigned counter_t n = 5;
      |                        ^

The corrected version decides signedness inside the typedef, and gives the structure a tag so the pointer member can refer to it.

#include <stdio.h>

typedef unsigned int counter_t;          /* signedness decided inside the typedef */

typedef struct node {                    /* tag 'node' lets the pointer refer to itself */
    counter_t    value;
    struct node *next;
} node_t;

int main(void)
{
    node_t second = {20u, NULL};
    node_t first  = {10u, &second};

    for (const node_t *p = &first; p; p = p->next) {
        printf("%u\n", p->value);
    }
    return 0;
}
10
20
Why the tag is needed
struct node { … struct node *next; }→tag exists inside the body→node_t named afterwards

Troubleshooting Checklist

SymptomCheck this first
invalid operands to binary ==Compare members, not whole structures
invalid use of undefined typeIs the structure defined at file scope or in a header?
Union value looks randomWhich member was written last?
sizeof larger than expectedPadding for alignment; print offsetof of each member
unknown type name in a self-referencing structureAdd a structure tag
Different results on another CPUEndianness and padding

Best Practices

  • Put structure and union definitions in headers, never inside function bodies.
  • Write a small compare function per structure instead of using memcmp.
  • Print sizeof and offsetof while designing a layout, and add a compile-time check with _Static_assert for layouts that must not change.
  • Track which union member is active with an explicit tag field.
  • Give every self-referencing structure a tag name, then optionally add a typedef.

Performance and security notes:

Padding wastes memory but keeps accesses fast. Structures copied to a network or file should be serialised member by member, not written as raw bytes, to avoid leaking uninitialised padding contents and to stay portable between machines.

Summary and Key Takeaways

  • Structures can be assigned but not compared with ==.
  • Padding makes sizeof larger than the sum of members; ask the compiler.
  • A type declared inside a function is invisible elsewhere.
  • A union has one storage area; the last written member is the meaningful one.
  • typedef names cannot take unsigned or long; self-referencing structures need a tag.

Conclusion

The structure and union chapter is now complete. You can model records, sort them, link them, search them and, just as important, predict why a program fails to compile or behaves oddly. Use the quiz below to check yourself and the interview questions to prepare for fresher and embedded firmware interviews. With this lecture the structure chapter of the free C programming course is finished, and the next topic can start from a clean slate.

Quiz: Test Yourself

Try each question before opening the answer.

  1. Which of these correctly tests whether two structure variables a and b hold the same data?
    A) a == b   B) a.x == b.x && a.y == b.y   C) a = b   D) a && b
    Show answer

    B. Compare members one by one. Option A is a compile error, C is an assignment, D is invalid.

  2. A structure struct s { char c; int i; }; typically has which size on a 32-bit or 64-bit Linux system?
    A) 5   B) 8   C) 4   D) 16
    Show answer

    B. One byte for c, three bytes of padding, four bytes for i.

  3. You define struct point inside main() and use it in function show(). What happens?
    A) Works   B) Compile error because the type is not visible   C) Link error   D) Runtime crash
    Show answer

    B. The structure has block scope inside main, so show() cannot see it.

  4. What is the size of union u { char a[15]; int b; }; on a typical system?
    A) 15   B) 4   C) 16   D) 19
    Show answer

    C. The largest member is 15 bytes; the union is rounded up to a multiple of its alignment, 4, giving 16.

  5. After v.f = 1.0f; on the union view from this lecture, what does v.bits hold on an IEEE-754 machine?
    A) 1   B) 0   C) 0x3F800000   D) undefined compile error
    Show answer

    C. The same four bytes read as an unsigned 32-bit integer.

  6. Which declaration is invalid?
    A) typedef int counter_t;   B) unsigned counter_t n;   C) typedef unsigned int u32;   D) counter_t n;
    Show answer

    B. A type specifier such as unsigned cannot be combined with a typedef name.

  7. Why does a self-referencing structure need a tag?
    A) For speed   B) The typedef name is not yet declared inside the body   C) To save memory   D) It does not
    Show answer

    B. Inside the braces the typedef name does not exist, so the pointer member must use struct tag *.

  8. Which header provides offsetof?
    A) stdio.h   B) stdlib.h   C) stddef.h   D) string.h
    Show answer

    C. stddef.h.

  9. Why is memcmp() on two structures unreliable?
    A) It is slow   B) Padding bytes can differ even when members are equal   C) It needs pointers   D) It is not in the standard
    Show answer

    B. Padding contents are indeterminate.

  10. When joining list b after list a with one pointer assignment, who should free the nodes of b?
    A) The joined list’s owner, once   B) Both owners   C) Nobody   D) The compiler
    Show answer

    A. The nodes now belong to the joined list; freeing b separately would be a double free.

Interview Questions on Structures and Unions

  1. What is the difference between a structure and a union?
    Show answer

    A structure gives every member its own storage; its size is at least the sum of the member sizes. A union overlays all members on one storage area; its size is that of the largest member, and only one member is meaningful at a time.

  2. Why can’t you compare two structures with ==?
    Show answer

    The language defines no member-wise or byte-wise comparison, and padding bytes make byte-wise comparison unreliable. You write a function that compares the relevant members.

  3. What is structure padding and why does it exist?
    Show answer

    The compiler inserts unused bytes so each member sits on an address suited to its type. Aligned access is faster or required by the hardware.

  4. How do you reduce padding?
    Show answer

    Order members from the largest alignment to the smallest, group small members together, or in special cases use a packed attribute and accept slower or restricted unaligned access.

  5. What does offsetof do?
    Show answer

    It yields the byte offset of a member from the start of its structure. It is used to verify layouts and in container-style macros.

  6. What are the scope rules for a structure definition?
    Show answer

    A structure type has the scope of the block where it is declared. Definitions needed by several functions or files belong at file scope or in a shared header.

  7. How does a self-referencing structure work?
    Show answer

    It contains a pointer to its own type, declared with the structure tag. Linked lists and trees are built this way.

  8. Why use a tag together with typedef?
    Show answer

    The tag lets the structure refer to itself before the typedef name exists, and it allows forward declarations.

  9. Give an embedded use for a union.
    Show answer

    Viewing a 32-bit register as a whole word and as individual bytes, or holding different message payloads selected by a type field. Beware of endianness and implementation-defined behaviour.

  10. When would you choose a linked list over an array?
    Show answer

    When you insert or remove often in the middle and do not know the size in advance. Arrays win for indexed access and cache-friendly traversal.

  11. How would you detect a loop in a singly linked list?
    Show answer

    Walk with a slow pointer and a fast pointer that moves two nodes at a time; if they ever meet, the list has a cycle.

  12. What happens if you free a joined list and its second part too?
    Show answer

    Double free: undefined behaviour, often an abort. Free the combined list exactly once.

Frequently Asked Questions

Can I assign one structure to another?

Yes, if they are the same type. All members, including arrays inside the structure, are copied.

Is the order of members important for size?

Yes. The same members in a different order can produce a different amount of padding and a different sizeof.

Is reading a different union member undefined behaviour?

In C11 the bytes are reinterpreted and the value is implementation-defined, but it can be a trap representation for some types. In C++ it is not allowed.

Does sizeof include padding at the end?

Yes. Trailing padding makes arrays of the structure keep every element aligned.

Why does my structure size differ between PC and microcontroller?

Integer sizes, alignment rules and packing defaults differ between targets. Always check on the real target.

Where can I practise more?

Re-implement each lecture’s program with your own data, then add a new feature such as deleting a node or sorting by marks.

Keep Learning C for Free

The structure chapter is complete. Revisit the course index and continue your free embedded C course journey.

<
💬 Need help or career guidance? Ask us!Contact Us →

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →