Skip to content
Unit 5 Syllabus Note· Programming with C Theory

Programming with C

Comprehensive exam revision notes for BCA-103N Unit 5 (Pointers, Structures, Unions & Dynamic Memory Allocation). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

Programming with C

Pointers, Structures, Unions & Dynamic Memory Allocation

Core Definitions & Key Concepts

What is a Pointer variable in C

A variable that stores the physical memory address of another variable of a specific data type.

The Address-of (&) and Dereference / Indirection (*) operators

&x: Returns the memory address where variable x is located. *ptr: Accesses or modifies the value stored at the memory address held inside pointer ptr.

What is a NULL Pointer

A pointer that does not point to any valid memory location, initialized to constant NULL (value 0). Used to prevent wild pointer errors and indicate end-of-list conditions.

What is a Generic Pointer (void *) in C

A pointer without an associated data type that can hold the address of any object (e.g. return type of malloc). It must be explicitly type-cast before dereferencing.

Pointer Arithmetic: What does ptr + 1 mean

Adding integer n to a pointer increments its address by n * sizeof(target_data_type). For an int * on a 4-byte system at address 1000, ptr + 1 points to address 1004.

What is a Structure in C

A user-defined composite data type that allows grouping variables of different data types together under a single name using the struct keyword.

What is the difference between the Dot operator (.) and Arrow operator (->)

Dot (`.`): Used to access structure members from a direct structure variable (s1.roll_no). Arrow (`->`): Used to access structure members through a pointer to a structure (s_ptr->roll_no).

What is the fundamental difference between a struct and a union

`struct`: Each member is allocated its own distinct memory; total size is the sum of members (plus padding). `union`: All members share the exact same memory location; total size is equal to the size of its largest member.

Dynamic Memory Allocation (DMA)

Allocating and freeing memory dynamically at runtime from the system Heap, allowing programs to resize memory based on actual runtime needs.

What is a Memory Leak and how is it prevented

A memory leak occurs when dynamically allocated heap memory (malloc) is no longer needed but never released via free(). Prevention: Always call free(ptr) when done and set ptr = NULL.

Conceptual & Architectural Analysis

Compare malloc(), calloc(), realloc(), and free() in <stdlib.h>

FunctionPrototypeAllocation & InitializationFailure Return
`malloc()`void* malloc(size_t size);Allocates raw uninitialized chunk of size bytes (contains garbage)Returns NULL
`calloc()`void* calloc(size_t n, size_t size);Allocates n * size bytes and initializes every byte to zero (`0`)Returns NULL
`realloc()`void* realloc(void *ptr, size_t new_size);Resizes existing heap block, preserving previous data contentsReturns NULL
`free()`void free(void *ptr);Deallocates heap block back to system memory poolReturns nothing (void)

Pointers and 1D Arrays Equivalence with code

In C, an array name is equivalent to a constant pointer to its first element: arr == &arr[0].

C
1int arr[3] = {10, 20, 30};
2int *ptr = arr;
3// *(arr + i) is identical to arr[i] and ptr[i] and *(ptr + i)
4printf("%d == %d\n", arr[1], *(ptr + 1)); // Prints 20 == 20

Structure Padding and Memory Alignment in C

To optimize CPU memory bus fetch efficiency, compilers align data types on natural byte boundaries (e.g., 4-byte ints aligned on 4-byte boundaries). Unused filler bytes (padding) are inserted between struct members.

C
1struct Example {
2 char a; // 1 byte
3 // 3 bytes padding inserted here!
4 int b; // 4 bytes
5 char c; // 1 byte
6 // 3 bytes padding inserted at end!
7}; // Total sizeof = 12 bytes (not 6 bytes!)

Dangling Pointers, Wild Pointers, and Void Pointers

  • Wild Pointer: An uninitialized pointer pointing to random, arbitrary memory.
  • Dangling Pointer: A pointer pointing to a memory location that has already been deallocated/freed.
  • *Void Pointer (`void `):** A generic pointer holding an address without a specified type; cannot be dereferenced directly without casting.

Pointers to Functions (Function Pointers) and their applications

A function pointer stores the starting memory address of executable code for a function.

C
1int add(int a, int b) { return a + b; }
2// Declare function pointer:
3int (*fptr)(int, int) = add;
4// Invoke through pointer:
5int result = fptr(10, 20); // result = 30

Used for callback functions and event-driven dispatch tables.

In-Depth Analysis & Implementation

Write a complete C program managing a Dynamic Array of Structures using malloc(), realloc(), and free() for Student Record Management

System Architecture / Concept DiagramHorizontal Scroll Enabled
/**
 * Program: Dynamic Student Database Management
 * Demonstrates: Structures, Dynamic Memory Allocation, Pointers, Arrow Operator
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student {
    int roll_no;
    char name[50];
    float marks;
};

int main(void) {
    int n, i;
    struct Student *students = NULL;

    printf("Enter initial number of students: ");
    scanf("%d", &n);

    // Allocate dynamic array on the Heap
    students = (struct Student *)malloc(n * sizeof(struct Student));
    if (students == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // Input records
    for (i = 0; i < n; i++) {
        printf("\nEnter details for Student %d:\n", i + 1);
        printf("Roll Number: ");
        scanf("%d", &(students + i)->roll_no);
        printf("Full Name: ");
        scanf(" %49[^\n]", (students + i)->name);
        printf("Marks: ");
        scanf("%f", &(students + i)->marks);
    }

    // Display records
    printf("\n===================================================\n");
    printf("             STUDENT ROSTER RECORDS                \n");
    printf("===================================================\n");
    printf("%-10s %-30s %-10s\n", "Roll No", "Name", "Marks");
    printf("---------------------------------------------------\n");
    for (i = 0; i < n; i++) {
        printf("%-10d %-30s %-10.2f\n",
               (students + i)->roll_no,
               (students + i)->name,
               (students + i)->marks);
    }

    // Clean up heap memory
    free(students);
    students = NULL; // Prevent dangling pointer
    printf("\nHeap memory successfully released.\n");

    return 0;
}

Provide an exhaustive comparison between Structures and Unions in C: Memory Allocation, Member Access, and Hardware Register Application

1. Conceptual Distinction

  • Structure: Aggregates distinct data members where each member has its own independent memory address. All members can hold valid values simultaneously.
  • Union: Memory-conserving composite type where all members share the same starting memory address. Only one member can hold a valid value at any given moment.

2. Side-by-Side Comparison Matrix

Featurestructunion
Keywordstructunion
Memory AllocationSum of sizes of all members (plus alignment padding)Equal to size of the largest member
Member StorageSeparate unique memory addresses for each memberIdentical shared base memory address
Concurrent AccessAll members accessible concurrentlyOnly one member active at any time
Alteration ImpactChanging one member does not affect othersOverwriting one member corrupts other members' values

3. Concrete Code Demonstration

C
1#include <stdio.h>
2
3struct S {
4 int i; // 4 bytes
5 char c; // 1 byte
6 double d; // 8 bytes
7}; // Total sizeof = 16 bytes (with 4-byte padding)
8
9union U {
10 int i; // 4 bytes
11 char c; // 1 byte
12 double d; // 8 bytes
13}; // Total sizeof = 8 bytes (size of double!)
14
15int main(void) {
16 union U u;
17 u.d = 3.14159;
18 printf("Union double: %lf\n", u.d);
19 u.i = 42; // Overwrites the double!
20 printf("Union int: %d (double is now corrupted!)\n", u.i);
21 return 0;
22}

Memory Architecture of a C Program: Code/Text Segment, Data Segment (BSS/Initialized), Stack, and Heap

System Architecture / Concept DiagramHorizontal Scroll Enabled
+------------------------------------------------+
| HIGH MEMORY (0xFFFFFFFF)                       |
| Stack Segment (Grows Downward)                 |
| - Local automatic variables, stack frames      |
|                        |                       |
|                        v                       |
|                       ...                      |
|                        ^                       |
|                        |                       |
| Heap Segment (Grows Upward)                    |
| - Dynamic memory allocated via malloc/calloc   |
+------------------------------------------------+
| BSS Segment (Uninitialized Global/Static)      |
| - Zero-initialized by OS before main()         |
+------------------------------------------------+
| Initialized Data Segment                       |
| - Global and static variables with initializers|
+------------------------------------------------+
| Text / Code Segment (Read-Only)                |
| - Executable binary CPU machine instructions   |
| LOW MEMORY (0x00000000)                        |
+------------------------------------------------+

Important Exam Points & Quick Revision

In BCA-103N Unit 5, questions on malloc vs calloc vs realloc, Structure vs Union, and the C Memory Layout diagram are virtually guaranteed in Section B and C.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Pointers, Structures, Unions & Dynamic Memory Allocation.

Weak topic hint

Pointers, Structures, Unions & Dynamic Memory Allocation still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.