PadhaikoAll subjects

Structures

Computer Programming (ENCT 101)

Open in the Padhaiko app

8.1 Defining a structure

While an array groups elements of the same data type, real-world records (such as a student's roll number, name, and GPA) combine fields of different types. A structure (struct) is a user-defined heterogeneous composite data type that groups logically related variables of potentially different types under a single name.

Definition

Structure Definition Syntax

A structure definition acts as a blueprint (template) and does not allocate memory by itself until structure variables are declared:

Defining a Student StructureC
struct Student {
    int roll;
    char name[30];
    float gpa;
};

Note the mandatory semicolon ; after the closing brace }! Using typedef struct { ... } Student; creates a type alias so variables can be declared simply as Student s1; without repeating struct.

AspectArrayStructure (struct)
Element TypesHomogeneous (all elements must have the same data type)Heterogeneous (members may have different types: int, char[], float, pointers)
Element AccessAccessed by integer index (arr[0], arr[1])Accessed by member name (s.roll, ptr->gpa)
Memory LayoutContiguous elements with no inter-element paddingContiguous members in declaration order, possibly with alignment padding bytes between or after members
Assignment (=)Cannot assign whole arrays directly (a = b; is illegal)Whole-structure assignment (s2 = s1;) copies all members cleanly

8.2 Declaring and accessing structure elements

Declaring Structure Variables:

  1. Separate from definition: struct Student s1, s2;
  2. Combined with definition: struct Point { int x; int y; } p1, p2;

Accessing Structure Members:


8.3 Initializing structure

Structure variables can be initialized at declaration time using brace-enclosed lists matching member declaration order, or via C99 designated initializers:


8.4 Array of structure

To store multiple records of the same structure type (e.g., 60 students in a class), declare an array of structures:

Array of Structures ExampleC
struct Student cls[3] = {
    {1, "Nisha", 3.60f},
    {2, "Rohan", 3.85f},
    {3, "Sita",  3.72f}
};
/* Accessing second student's GPA: */
printf("%.2f\n", cls[1].gpa);

Each element cls[i] is a full struct Student stored contiguously in memory, so sizeof(cls) == 3 * sizeof(struct Student).


8.5 Array as member to structure

A structure frequently contains arrays as individual fields—for instance, a character array for a string name or an integer array for subject marks:

Array Inside a StructureC
struct ExamRecord {
    int roll;
    char name[40];      /* char array member */
    int marks[5];       /* int array member */
};

struct ExamRecord r = {12, "Kiran", {78, 84, 91, 69, 88}};
/* Access 3rd subject mark: r.marks[2] -> 91 */

Because arrays inside a struct are fixed-size value members, copying r2 = r1; copies the entire embedded array contents too!


8.6 Pointer as member to structure

A structure can hold pointer members pointing to dynamically allocated buffers or to other structures of the same type (self-referential structures, which form linked lists and trees):

Pointer Members and Self-Referential StructureC
struct Node {
    int data;
    char *label;            /* pointer to external string */
    struct Node *next;      /* self-referential pointer */
};

8.7 Structure as a member to structure

A nested structure embeds one structure variable inside another structure to model hierarchical records cleanly (such as an Employee containing a Date of joining).

Nested Structure Definition and Member ChainingC
struct Date {
    int day, month, year;
};

struct Employee {
    int id;
    char name[30];
    struct Date join_date;  /* nested struct member */
};

struct Employee e = {10, "Prakash", {15, 8, 2024}};
/* Access chained via multiple dots: e.join_date.year -> 2024 */

8.8 Passing and returning structures to/from function

Structures can interact with functions in three ways:

  1. Passing Individual Members: display_gpa(s.gpa); (passes only one field by value).
  2. Passing Whole Structure by Value: void print_student(struct Student s); copies the entire structure onto the call stack; modifications inside the function do not affect the caller's original variable.
  3. Passing Structure Pointer (Call by Reference): void update_gpa(struct Student *p, float g); passes only the address (&s), avoiding expensive copies of large records and allowing the function to modify p->gpa directly. Use const struct Student *p for read-only efficiency.
  4. Returning a Structure: A function can return a struct by value (struct Point add_points(struct Point a, struct Point b);) to return multiple grouped values cleanly.

Worked Examples

Example 1

1 (6 marks)

Define a nested structure struct Student containing int roll, char name[30], struct Date dob (day, month, year), and an array member int marks[3]. Write a C program with an array of 2 students that computes and prints each student's average marks using a function taking const struct Student *.

Structure Definitions and Prototype: Define struct Date first so struct Student can embed struct Date dob; directly as a member. Pass const struct Student *s to print_report() to avoid copying the entire structure while keeping it read-only.

Nested Structure, Array of Structs, and Pointer PassingC
#include <stdio.h>

struct Date {
    int day, month, year;
};

struct Student {
    int roll;
    char name[30];
    struct Date dob;
    int marks[3];
};

double avg_marks(const struct Student *s) {
    int total = 0;
    for (int i = 0; i < 3; i++) {
        total += s->marks[i];
    }
    return total / 3.0;
}

int main(void) {
    struct Student batch[2] = {
        {101, "Ananya", {12, 5, 2005}, {80, 90, 85}},
        {102, "Bikash", {23, 11, 2004}, {70, 75, 80}}
    };
    for (int i = 0; i < 2; i++) {
        printf("%d %s (%02d-%02d-%d): avg=%.2f\n",
               batch[i].roll, batch[i].name,
               batch[i].dob.day, batch[i].dob.month, batch[i].dob.year,
               avg_marks(&batch[i]));
    }
    return 0;
}

Tracing Calculations:

  • Student 1 (Ananya): (80 + 90 + 85) / 3.0 = 255 / 3.0 = 85.00.
  • Student 2 (Bikash): (70 + 75 + 80) / 3.0 = 225 / 3.0 = 75.00.
Answer:

Output:

Program OutputText
101 Ananya (12-05-2005): avg=85.00
102 Bikash (23-11-2004): avg=75.00
Example 2

2 (6 marks)

Write a C function struct Complex add_complex(struct Complex c1, struct Complex c2) that accepts two structures representing complex numbers (real and imag doubles) by value and returns their sum as a struct Complex. Trace it for (4 + 7i) and (6 + 9i).

Returning a Structure from a Function:

Adding Two Complex Numbers Using Structure ReturnC
#include <stdio.h>

struct Complex {
    double real;
    double imag;
};

struct Complex add_complex(struct Complex c1, struct Complex c2) {
    struct Complex res;
    res.real = c1.real + c2.real;
    res.imag = c1.imag + c2.imag;
    return res;
}

int main(void) {
    struct Complex a = {4.0, 7.0};
    struct Complex b = {6.0, 9.0};
    struct Complex sum = add_complex(a, b);
    printf("%.1f + %.1fi\n", sum.real, sum.imag);
    return 0;
}

Tracing Member-by-Member Addition:

  • res.real = 4.0 + 6.0 = 10.0
  • res.imag = 7.0 + 9.0 = 16.0

return res; returns a struct Complex copy containing {10.0, 16.0} to sum in main().

Answer:

Output: 10.0 + 16.0i.

Example 3

3 (5 marks)

Trace the output of the following C program that mixes structure pointers (->), pointer members inside a structure, and call-by-value vs. call-by-address structure parameters:

Structure Pointer vs Value Mutation TraceC
#include <stdio.h>

struct Box {
    int count;
    int *val_ptr;
};

void by_val(struct Box b) {
    b.count += 10;
    *(b.val_ptr) += 4;
}

void by_ptr(struct Box *p) {
    p->count += 4;
}

int main(void) {
    int x = 2;
    struct Box box = {4, &x};
    by_val(box);
    by_ptr(&box);
    printf("count=%d x=%d\n", box.count, x);
    return 0;
}

Tracing by_val(box): by_val receives a shallow copy b of box: b.count is 4 (a copy) and b.val_ptr holds &x (copied address pointing to x in main()).

  • b.count += 10; changes only local copy b.count to 14; box.count in main() stays 4.
  • *(b.val_ptr) += 4; dereferences &x, modifying x directly from 2 to 6.

Tracing by_ptr(&box): p points directly to box in main(). p->count += 4; updates box.count from 4 to 8.

Answer:

Output: count=8 x=6. Notice that passing a structure by value still allows modifying external data referenced by a pointer member inside that structure!


Exercises

Exercises — Structures

Question 1

What is a structure in C, and how does it differ from an array? Write the syntax to define a structure and declare variables using typedef.

Definition and Comparison: A structure (struct) is a user-defined heterogeneous data type grouping variables of different types under one name, accessed by member identifiers (. or ->). An array is a homogeneous collection of same-typed elements accessed by integer indices. Unlike arrays, structures support direct whole-variable assignment (s2 = s1;).

typedef Structure Syntax:

typedef Structure DefinitionC
typedef struct {
    int id;
    char title[50];
    float price;
} Book;

Book b1 = {10, "ANSI C", 450.0f};
Answer:

A struct groups heterogeneous members accessed by name (./->), whereas an array stores homogeneous elements accessed by index. Using typedef struct { ... } TypeName; lets variables be declared directly as TypeName var;.

Question 2

Distinguish between the dot operator (.) and the arrow operator (->) when accessing structure members. Why does *ptr.member fail to compile if parentheses are omitted?

Dot (.) vs. Arrow (->):

  • The dot operator . accesses a member of a structure variable directly (s.roll).
  • The arrow operator -> accesses a member through a pointer to a structure (ptr->roll), automatically dereferencing ptr.

Precedence Trap in *ptr.member: In C, . has higher precedence than unary *. Without parentheses, *ptr.member parses as *(ptr.member), which fails because ptr is a pointer, not a structure. Writing (*ptr).member fixes precedence and is identical to ptr->member.

Answer:

Use . on structure variables (s.x) and -> on structure pointers (ptr->x). *ptr.member fails because . binds tighter than *, parsing as *(ptr.member); parentheses (*ptr).member or ptr->member are required.

Question 3

Explain an array of structures vs. an array as a member of a structure. Write a short C snippet defining struct Item { char name[20]; int qty; float rate; }; for 3 items and compute the total bill amount for {(A, 2, 50), (B, 4, 50), (C, 3, 100)}.

Array of Structures vs. Array Inside Structure:

  • Array of structures (struct Item cart[3];) creates multiple independent structure records in contiguous memory.
  • Array as member (char name[20]; inside struct Item) embeds an array inside each individual structure record.

Bill Computation:

Total Bill Using Array of StructuresC
struct Item {
    char name[20];
    int qty;
    float rate;
};

struct Item cart[3] = {{"A", 2, 50.0f}, {"B", 4, 50.0f}, {"C", 3, 100.0f}};
float total = 0.0f;
for (int i = 0; i < 3; i++) {
    total += cart[i].qty * cart[i].rate;
}

Sum: 2 * 50 + 4 * 50 + 3 * 100 = 100 + 200 + 300 = 600.00.

Answer:

An array of structures stores a list of records (cart[i].qty), while an array member stores a collection inside each record (cart[i].name[0]). Total bill = 600.00.

Question 4

Compare passing a structure to a function by value versus passing a pointer to a structure (struct S *) with respect to memory efficiency and mutability.

Memory and Mutability Trade-offs:

  • By Value (void f(struct S x)): Copies every byte of struct S (including embedded arrays) onto the call stack. Large structures waste stack space and CPU copy time, and changes to x inside f do not alter the caller's variable.
  • By Pointer (void f(struct S *p)): Copies only a single memory address (4 or 8 bytes), regardless of structure size. Allows in-place updates via p->field (or safe read-only access when declared const struct S *p).
Answer:

Passing by value copies the entire structure and isolates the caller's data; passing a structure pointer passes only an address (fast for large structs) and permits direct modification via -> unless marked const.

Question 5

What is a nested structure and what is a self-referential structure? Give a brief C declaration example of each and state one practical use of each.

Nested Structure vs. Self-Referential Structure:

  1. Nested Structure: One structure contains a variable of another structure type as a member (e.g., struct Student { int id; struct Date dob; };). Used to compose hierarchical records cleanly.
  2. Self-Referential Structure: A structure contains a pointer to its own type (e.g., struct Node { int val; struct Node *next; };). (Note: a struct cannot contain itself directly by value, only a pointer to itself.) Used to build dynamic linked lists, stacks, queues, and binary trees.
Answer:

A nested structure embeds another struct type by value to model composite records (e.g., Date inside Student), whereas a self-referential structure embeds a pointer to its own type (struct Node *next) to link dynamic nodes in lists and trees.

← User-defined FunctionsFile Management →