Skip to content
StudyFame

Structures in C

A student has a roll number (int), a name (string) and a CGPA (float). An array can't hold these together, because an array stores only one type. A structure can.

In this lesson you will create your own data type with struct, store a student's details in one variable, and learn how to declare, initialize, access and copy structures. Structures are the base of records, files and linked lists, so this lesson matters a lot.

What You Will Learn

  • What a structure is and why we need it.
  • How to define a structure type.
  • How to declare structure variables.
  • How to access members with the dot (.) operator.
  • How to initialize and copy structures.
  • How the size of a structure is decided (padding).

What is a Structure in C?

Exam definition: A structure is a user-defined data type that groups variables of different data types under one name. Each variable inside it is called a member (or field), and members are accessed with the dot operator (.).

Memory trick: A structure is like an admission form. The blank form (the struct definition) has fields: Roll No, Name, CGPA. Every student fills their own copy (a structure variable). Array = many boxes of the same kind; structure = one form with different kinds of boxes.

Syntax of a Structure

struct student              /* struct tag: the name of the new type */
{
    int   roll;             /* members */
    char  name[30];
    float cgpa;
};                          /* semicolon is required! */

struct student s1;          /* declare a variable */
struct student s2 = {101, "Asha", 8.6f};          /* initialize in order */
struct student s3 = {.cgpa = 9.1f, .roll = 102};  /* designated (C99) */

s1.roll = 103;              /* access with the dot operator */
  • Defining the struct creates a type, not a variable. No memory is used until you declare a variable.
  • The type's full name is struct student (both words). typedef can shorten it; you'll learn that later in this module.
  • Members not given in an initializer become 0 (or an empty string).

Example 1: Store and Print a Student Record

#include <stdio.h>
#include <string.h>

struct student
{
    int roll;
    char name[30];
    float cgpa;
};

int main(void)
{
    struct student s1 = {101, "Asha Verma", 8.6f};
    struct student s2;

    s2.roll = 102;                       /* set members one by one */
    strcpy(s2.name, "Ravi Kumar");       /* strings need strcpy */
    s2.cgpa = 7.9f;

    printf("Roll  Name         CGPA\n");
    printf("%-5d %-12s %.1f\n", s1.roll, s1.name, s1.cgpa);
    printf("%-5d %-12s %.1f\n", s2.roll, s2.name, s2.cgpa);

    if (s1.cgpa > s2.cgpa)
        printf("Topper: %s\n", s1.name);

    return 0;
}

Output

Roll  Name         CGPA
101   Asha Verma   8.6
102   Ravi Kumar   7.9
Topper: Asha Verma

Code Explanation

  1. struct student { ... }; defines a new type with three members. It's written outside main so every function can use it.
  2. s1 is initialized in member order: roll, name, cgpa.
  3. s2 is filled member by member. s2.name = "Ravi" would be an error (arrays can't be assigned), so we use strcpy.
  4. s1.cgpa reads "the cgpa member of s1". Members are used like normal variables.

Practice: store student information in a structure and display it.

How a Structure is Stored in Memory

Members are stored in order, one after another. But the compiler may add unused bytes, called padding, so that each member starts at an address the CPU can read quickly (for example, an int at a multiple of 4).

struct demo { char c; int i; char d; };     (typical 64-bit system)

offset: 0    1  2  3   4  5  6  7   8    9 10 11
       [c] [pad pad pad][   i    ] [d] [pad pad pad]
sizeof(struct demo) = 12, not 1 + 4 + 1 = 6

Reordered: struct demo2 { int i; char c; char d; };
offset: 0  1  2  3   4   5   6  7
       [   i    ]  [c] [d] [pad pad]
sizeof(struct demo2) = 8

So sizeof(struct) ≥ sum of member sizes. Placing bigger members first often saves memory.

Example 2: Copying Structures, Comparing and sizeof

#include <stdio.h>

struct point
{
    int x;
    int y;
};

struct demo  { char c; int i; char d; };
struct demo2 { int i; char c; char d; };

int main(void)
{
    struct point a = {3, 4};
    struct point b;

    b = a;                       /* whole structure copied at once */
    b.x = 10;                    /* changing b doesn't change a */
    printf("a = (%d, %d), b = (%d, %d)\n", a.x, a.y, b.x, b.y);

    /* if (a == b) is NOT allowed: compare member by member */
    if (a.x == b.x && a.y == b.y)
        printf("a and b are equal\n");
    else
        printf("a and b are different\n");

    printf("sizeof(struct point) = %zu\n", sizeof(struct point));
    printf("sizeof(struct demo)  = %zu\n", sizeof(struct demo));
    printf("sizeof(struct demo2) = %zu\n", sizeof(struct demo2));

    return 0;
}

Output

a = (3, 4), b = (10, 4)
a and b are different
sizeof(struct point) = 8
sizeof(struct demo)  = 12
sizeof(struct demo2) = 8
  • b = a; copies every member, even arrays inside the struct. This works for structures, unlike plain arrays.
  • a == b is a compile error. Compare the members you care about.
  • The sizes show padding: demo and demo2 have the same members, but different order gives 12 vs 8 bytes. (Sizes can differ on other systems.)

Array vs Structure

PointArrayStructure
Data typesAll the sameCan be different
AccessBy index: a[2]By name: s.cgpa
Assign whole thing with =NoYes
TypeDerived (built from one type)User-defined
Typical useList of marksOne student's record

Important Points to Remember

  • A structure groups different types under one name.
  • End the definition with a semicolon: };
  • Defining a struct creates a type; memory comes with variables.
  • Access members with the dot operator: s.roll.
  • Structures can be copied with = but not compared with ==.
  • sizeof(struct) may be larger than the sum of members because of padding.

Common Mistakes Beginners Make

MistakeWhat happensFix
Missing ; after }Confusing compile errors on the next lineWrite };
student s1; (without struct)Error: unknown typestruct student s1; or use typedef
s.name = "Ravi";Error: array not assignablestrcpy(s.name, "Ravi");
if (s1 == s2)Compile errorCompare members
Initializing members inside the definition: int roll = 0;Compile error in CInitialize the variable, not the type

Structures in C Practice Questions

  1. Define a structure. How is it different from an array?
  2. Write a structure book with title (40 chars), author (30 chars) and price (float).
  3. Which operator accesses a structure member?
  4. Can two structure variables be compared with ==? Can they be assigned with =?
  5. Why can sizeof of a structure be more than the sum of its members?
Show answers
  1. A user-defined type grouping members of different types under one name. An array holds elements of one type accessed by index.
  2. struct book { char title[40]; char author[30]; float price; };
  3. The dot operator .
  4. No for ==; yes for = (all members are copied).
  5. The compiler adds padding bytes so members are properly aligned in memory.

Coding Exercise

Create a structure employee with id, name and salary. Store one employee, give a 10% raise using the member, and print the details before and after.

Show solution
#include <stdio.h>

struct employee
{
    int id;
    char name[30];
    float salary;
};

int main(void)
{
    struct employee e = {7, "Kiran", 40000.0f};

    printf("Before: %d %s %.2f\n", e.id, e.name, e.salary);
    e.salary = e.salary * 1.10f;
    printf("After : %d %s %.2f\n", e.id, e.name, e.salary);
    return 0;
}
Before: 7 Kiran 40000.00
After : 7 Kiran 44000.00

Quick Quiz: Structures in C (MCQ)

  1. A structure can hold members of:

    A) Only int type   B) Only the same type   C) Different types   D) Only pointers

  2. Keyword used to define a structure:

    A) structure   B) struct   C) record   D) class

  3. Members of a structure variable are accessed with:

    A) ->   B) .   C) ::   D) []

  4. Which is invalid for structure variables a and b of the same type?

    A) a = b;   B) a.x = b.x;   C) if (a == b)   D) sizeof(a)

  5. Extra unused bytes added inside a structure are called:

    A) Padding   B) Overflow   C) Garbage   D) Offset

Show answers
  1. C: different types.
  2. B: struct.
  3. B: the dot operator.
  4. C: if (a == b).
  5. A: padding.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

StructureUser-defined type grouping different types
Keywordstruct; definition ends with };
Access memberDot operator: s.roll
s1 = s2Allowed: copies all members
s1 == s2Not allowed
sizeof(struct)≥ sum of members (padding)

Frequently asked questions

What is a structure in C?
A user-defined data type that groups related variables of different types under one name.
What is structure padding?
Unused bytes the compiler inserts so members are aligned for faster access; it makes sizeof bigger than the member total.
What is the difference between an array and a structure?
An array stores same-type elements by index; a structure stores different-type members by name.

Remember

  • Structure = admission form; variable = one filled copy.
  • Don't forget the semicolon after the closing brace.

Next Topic

Next lesson: Array of Structures in C. You will store records of many students in an array of structures.