Unit 4: Structures, pointers and file handling
Problem Solving Techniques notes · PTU syllabus (UGSEC2501)
On this page
Unit summary
Real data has many related fields, and programs need to talk directly to memory and files. This unit covers structures and user-defined data types, structures and pointers, passing structures to functions, unions, pointers (declaration, initialisation and access through a pointer, pointers and arrays), and file operations including processing a data file.
After this unit you can
- Define and process structures, nested structures and arrays of structures
- Use typedef and enum as user-defined types and write unions
- Declare pointers, use & and *, and relate pointers to arrays
- Pass structures and pointers to functions
- Open, read, write and close data files
PTU syllabus topics
- Defining and processing a structure
- user-defined data types
- structures and pointers
- passing structures to functions
- unions
- pointer declaration and initialization
- accessing a variable through its pointer
- pointers and arrays
- file operations and processing a data file
Topic 1
Structures
A structure groups variables of different types under one name.
cstruct Student {
int roll;
char name[20];
float marks;
};
struct Student s1 = {101, "Asha", 82.5};
printf("%d %s %.1f\n", s1.roll, s1.name, s1.marks); /* dot operator */Elements
Different types
Same type
Access
Member name — s.roll
Index — a[2]
Size
Sum of members (plus padding)
n × size of one element
Copying
One structure can be assigned to another
Only element by element
- Declaration
- struct tag { members }; creates a type
- Variable
- struct Student s1, s2;
- Initialisation
- In member order within braces
- Member access
- Dot operator s1.roll
- Assignment
- s2 = s1; copies all members
- Size
- sizeof(struct Student) may include padding bytes
- 1Declare the structure type
- 2Declare variables of that type
- 3Read each member with scanf (use & for non-strings)
- 4Process the members
- 5Print each member
Array of structures and nested structures
cstruct Student cls[3];
for (i = 0; i < 3; i++) { scanf("%d %s %f", &cls[i].roll, cls[i].name, &cls[i].marks); }
struct Date { int d, m, y; };
struct Emp { int id; struct Date joined; }; /* nested structure */
struct Emp e = {1, {15, 8, 2024}};
printf("%d", e.joined.y); /* 2024 */typedef and user-defined data types
typedef
typedef struct { int roll; float marks; } Student;
Gives a new name to a type — Student s1;
enum
enum Day {MON, TUE, WED};
Named integer constants
typedef with basic types
typedef unsigned int uint;
Shorter, clearer names
struct
struct Point {int x, y;};
Compound type
Topic 2
Structures and pointers; passing structures to functions
cstruct Student s = {101, "Asha", 82.5};
struct Student *p = &s;
printf("%d %s\n", p->roll, p->name); /* arrow operator: (*p).roll */Passing structures to functions
| Method | Effect |
|---|---|
| By value | void show(struct Student s) — copy of all members; original unchanged |
| By address | void update(struct Student *p) — original can change; use p->marks |
| Returning a structure | struct Student read(void) — returns a copy |
| Array of structures | Passed by address like any array |
cvoid update(struct Student *p) { p->marks += 5; } /* modifies the caller's structure */
struct Student best(struct Student a[], int n) { /* returns the topper */
int i, k = 0;
for (i = 1; i < n; i++) if (a[i].marks > a[k].marks) k = i;
return a[k];
}Used with
Structure variable
Pointer to structure
Example
s.roll
p->roll, same as (*p).roll
Example
Why pass a structure by address? show(s) copies every member of s — for a structure with a 100-character address field, that is over 100 bytes copied on each call, and any change inside the function is lost. update(&s) passes just one address (4 or 8 bytes), and p->marks += 5 changes the caller's structure. Pass by value when the function only reads small structures; pass by address when it must modify them or when they are large.
Topic 3
Unions
A union also groups members of different types, but all members share the same memory — only one is valid at a time; its size is that of the largest member.
cunion Data { int i; float f; char c; };
union Data d;
d.i = 65;
printf("%d %c\n", d.i, d.c); /* 65 A — shows how the same bytes are read as int and char */
printf("%zu\n", sizeof d); /* 4 */Memory
Separate space for every member
One shared space — size of the largest member
Members valid
All at once
One at a time
Size of {int, float, char}
12 bytes (with padding)
4 bytes
Keyword
struct
union
Use
Records
Saving memory, interpreting the same data in different ways
| struct { int i; float f; char c; } | Bytes 0–3 | Bytes 4–7 | Byte 8 |
|---|---|---|---|
| Layout | i | f | c (plus padding) |
| union { int i; float f; char c; } | Bytes 0–3 shared by i, f and c |
Exam tip
A favourite short question: size of a structure vs a union with the same members. The structure needs space for all members (plus padding); the union needs space only for its largest member. State that only the member written last in a union holds a valid value.
Topic 4
Pointers
A pointer is a variable that stores the address of another variable. Pointer operators
| Meaning | |
|---|---|
| & (address-of) | &x gives the address of x |
| * (declaration) | int *p; declares a pointer to int |
| * (dereference) | *p is the value at the address in p |
| NULL | A pointer that points nowhere — always initialise |
| Size of a pointer | Same for all types (4 or 8 bytes) |
cint x = 10;
int *p = &x; /* p holds the address of x */
printf("%d %d %p\n", x, *p, (void *) p);
*p = 25; /* changes x through the pointer — x is now 25 */p stores the address of x; *p reads or changes the value of x
- 1
Declare a variable x
- 2
Declare a pointer p of the same type
- 3
Initialise p = &x
- 4
Read the value with *p
- 5
Change x by assigning to *p
- 6
Never use an uninitialised pointer
- Initialisation
- Assign &variable, NULL or dynamically allocated memory
- Pointer arithmetic
- p + 1 moves by sizeof(type) bytes, not one byte
- Comparison
- Pointers can be compared with == and <
- Pointer to pointer
- int **pp = &p;
- Dangling pointer
- Points to freed or out-of-scope memory
- Dynamic memory
- malloc(n * sizeof(int)) and free(p) from stdlib.h
Example
Swapping two numbers — why pointers are needed: void swap(int a, int b) swaps only its own copies, so the caller's x and y do not change. void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } called as swap(&x, &y) works on the original variables: with x = 5 and y = 9, after the call x = 9 and y = 5.
Example
Tracing pointer output: int a[] = {10, 20, 30}; int *p = a; then printf("%d ", *p++); prints 10 and moves p to a[1]; printf("%d ", *++p); moves p to a[2] first and prints 30; printf("%d", ++*p); adds 1 to a[2] and prints 31. Read *p++ as "use the value, then move" and ++*p as "increase the value".
Pointers and arrays
cint a[4] = {10, 20, 30, 40};
int *p = a; /* same as &a[0] — array name is the address of the first element */
for (i = 0; i < 4; i++) printf("%d ", *(p + i)); /* 10 20 30 40 */| Expression | Meaning | Value (base address 1000) |
|---|---|---|
| a or &a[0] | Address of first element | 1000 |
| a + 1 or &a[1] | Address of second element | 1004 |
| *(a + 2) or a[2] | Value of third element | 30 |
| p++ | Pointer moves to next element | 1004 |
Element i
a[i]
*(a + i)
Address of element i
&a[i]
a + i
Can the name change?
No — a++ is an error
Yes — p++ is allowed
- char *s = "SBS"
- Pointer to a string literal (do not modify it)
- char s[] = "SBS"
- Modifiable array
- Traversal
- while (*s) { putchar(*s); s++; }
- Array of pointers
- char *names[3] — table of strings
Topic 5
File operations and processing a data file
Files store data permanently on disk, unlike variables that vanish when the program ends.
Content
Characters, readable
Raw bytes
Functions
fprintf, fscanf, fgets, fputs, fgetc, fputc
fread, fwrite
Size
Larger for numbers
Compact
Portability
Easy to read and edit
Faster, machine dependent
File opening modes
| Meaning | |
|---|---|
| "r" | Read — file must exist |
| "w" | Write — creates or erases an existing file |
| "a" | Append — adds at the end |
| "r+" | Read and write, file must exist |
| "w+" | Read and write, erases |
| "a+" | Read and append |
| Add b | "rb", "wb", "ab" for binary files |
- 1Declare a FILE pointer — FILE *fp
- 2Open the file with fopen and check for NULL
- 3Read or write with file functions
- 4Check end of file with feof
- 5Close the file with fclose
Common file functions
| Purpose | |
|---|---|
| fopen(name, mode) | Opens a file, returns a FILE pointer or NULL |
| fclose(fp) | Closes the file |
| fprintf and fscanf | Formatted write and read |
| fgetc and fputc | Read and write one character |
| fgets and fputs | Read and write a line |
| fread and fwrite | Read and write blocks of binary data |
| feof(fp) | Non-zero at end of file |
| fseek, ftell, rewind | Move and report the file position |
| remove and rename | Delete or rename a file |
c#include <stdio.h>
int main(void) {
FILE *fp;
int id; char name[20]; float salary;
fp = fopen("emp.txt", "w"); /* write employee records */
if (fp == NULL) { printf("Cannot open file\n"); return 1; }
fprintf(fp, "%d %s %.2f\n", 101, "Asha", 45000.0);
fprintf(fp, "%d %s %.2f\n", 102, "Ravi", 52000.0);
fclose(fp);
fp = fopen("emp.txt", "r"); /* read them back */
while (fscanf(fp, "%d %s %f", &id, name, &salary) == 3)
printf("%d %s %.2f\n", id, name, salary);
fclose(fp);
return 0;
}c/* binary file of structures */
struct Student s = {101, "Asha", 82.5};
FILE *fp = fopen("stud.dat", "wb");
fwrite(&s, sizeof(struct Student), 1, fp);
fclose(fp);
fp = fopen("stud.dat", "rb");
fread(&s, sizeof(struct Student), 1, fp);
fclose(fp);- FILE
- Structure type defined in stdio.h
- Standard streams
- stdin (keyboard), stdout (screen), stderr (errors)
- Error check
- fopen returns NULL on failure
- Positioning
- fseek(fp, 0, SEEK_SET) beginning, SEEK_END end
- Always close
- fclose flushes buffers and releases the file
- Sequential vs random access
- Read from start vs jump using fseek
Exam tip
Three mistakes examiners look for: forgetting & in scanf for non-string variables, using a FILE pointer without checking whether fopen returned NULL, and looping on while (!feof(fp)), which processes the last record twice — loop on the return value of fscanf or fgets instead, as in the program above.
Key terms
- Structure
- User-defined type grouping members of different types
- Member
- A variable inside a structure or union
- typedef
- Gives a new name to an existing type
- Union
- Members share the same memory location
- Pointer
- Variable holding the address of another variable
- Dereference
- Reading or writing the value a pointer points to using *
- Arrow operator
- Accesses a member through a pointer to a structure
- FILE pointer
- Handle used for file operations
- fopen and fclose
- Open and close a file
- EOF
- Marker for the end of a file
Quick revision
- struct: dot operator; array of structures; nested structures; typedef.
- Pointer to structure: arrow operator; structures pass by value or by address.
- union: shared memory, size of the largest member.
- Pointers: & gives the address, * gives the value; p + 1 moves one element; a[i] = *(a + i).
- File steps: FILE *fp → fopen → read/write → fclose; modes r, w, a.
- fprintf/fscanf for text; fread/fwrite for binary.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.Define a structure with a suitable example.
- Q2.Differentiate between structure and union.
- Q3.What is the use of typedef?
- Q4.Differentiate between the dot and arrow operators.
- Q5.What is a pointer? Write its declaration.
- Q6.What is the output of *(a + 2) for a = {10, 20, 30}?
- Q7.How can a structure be passed to a function?
- Q8.What are file opening modes "r", "w" and "a"?
- Q9.What does fopen return on failure?
- Q10.Name four file handling functions.
Long-answer questions
- Q1.Explain structures, arrays of structures and nested structures with a program.
- Q2.Explain unions and compare them with structures.
- Q3.Explain pointers and the relationship between pointers and arrays with examples.
- Q4.Explain how structures are passed to functions using values and pointers.
- Q5.Explain file operations and write a program to store and display employee details in a file.
- Q6.Explain text and binary files with reading and writing functions.
Stuck on this unit?
Message SBS on WhatsApp for help with Problem Solving Techniques, or to ask about studying BCA at Synetic.
