LearnFrenzy
Sign in Take a free test
C

C Programming · Topic 12 of 23

Structures, Unions, Enums Questions and Concepts

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Coding Techniques

Structures, Unions, Enums · Study material

Sorting an array of structures

Keep records in an array of structs and sort them with qsort(); the comparator casts its const void * arguments back to the struct type.

#include <stdio.h>
#include <stdlib.h>

struct emp {
    const char *name;
    int salary;
};

static int by_salary_desc(const void *a, const void *b) {
    const struct emp *x = a, *y = b;
    return (y->salary > x->salary) - (y->salary < x->salary);
}

int main(void) {
    struct emp team[] = {{"Asha", 72000}, {"Ravi", 95000}, {"Meera", 61000}, {"John", 88000}};
    qsort(team, 4, sizeof team[0], by_salary_desc);
    for (int i = 0; i < 4; i++)
        printf("%-6s %d\n", team[i].name, team[i].salary);
    return 0;
}

Output

Ravi   95000
John   88000
Asha   72000
Meera  61000

Bit-fields for compact flags

Bit-fields pack several small values into one word – handy for flags and hardware registers. The layout is implementation-defined, so do not use them for file or network formats.

#include <stdio.h>

struct perms {
    unsigned read  : 1;      /* one bit each */
    unsigned write : 1;
    unsigned exec  : 1;
};

int main(void) {
    struct perms p = {.read = 1, .exec = 1};
    printf("r=%u w=%u x=%u, sizeof = %zu\n", p.read, p.write, p.exec, sizeof p);
    return 0;
}

Output

r=1 w=0 x=1, sizeof = 4

X-macros: one list for the enum and its names

Write the list once and expand it twice – as enum constants and as strings – so the names can never get out of step with the values.

#include <stdio.h>

#define COLORS(X) X(RED) X(GREEN) X(BLUE)    /* the list, written once */
#define AS_ENUM(name) name,
#define AS_TEXT(name) #name,

enum color { COLORS(AS_ENUM) COLOR_COUNT };
static const char *color_name[] = { COLORS(AS_TEXT) };

int main(void) {
    for (int c = 0; c < COLOR_COUNT; c++)
        printf("%d %s\n", c, color_name[c]);
    return 0;
}

Output

0 RED
1 GREEN
2 BLUE

Comparing structures correctly

== does not work on structs, and memcmp() also compares padding bytes, whose values are unspecified. Write a comparison function.

#include <stdbool.h>
#include <string.h>

bool same_student(const struct student *a, const struct student *b) {
    return a->roll == b->roll && strcmp(a->name, b->name) == 0;
}

Good structure habits

  • Initialise with designated initializers: {.x = 1, .y = 2}.
  • Order members from largest to smallest alignment to cut padding.
  • Pass large structs as const struct t *.
  • Write a "deep copy" function when a struct owns heap memory.
  • Always store a tag with a union.
  • Use offsetof(), never hand-computed offsets.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links