Unit 4
Pointers & File Management in C
Pointer
● A pointer is a variable that stores the address of another
variable.
● Unlike other variables that hold values of a certain type, pointer
holds the address of a variable.
● For example, an integer variable holds an integer value,
however an integer pointer holds the address of a integer
variable.
datatype *pointer_name;
Pointer
A pointer is just a variable that stores an address instead Think of it as:
of a normal value.
● Locker A (for x) contains value 10
● Normal int variable → stores an integer value like 5,
10, 100… ● Locker B (for p) contains the locker
number of A
● int * pointer → stores the address of an int variable
So if:
So: ● Address of x is 1000
int x = 10; // x stores 10 ● Then:
int *p; // p is a pointer to int (stores address of an int)
○ x holds: 10
p = &x; // p now stores the address of x
○ p holds: 1000 (the address of x)
Pointer
+-----------+ +-----------+
x: | 10 | p: | 1000 | int x = 10;
+-----------+ +-----------+
int *p; // pointer to int
| ^
| | p = &x; // p stores address of x
+-----------------------+ x contains value 10
(p stores the address of x) p contains address of x
Address of x = 1000 (example)
*p gives value at that address → 10
Why pointers are used?
1. To access and modify variables indirectly
2. Efficient handling of arrays
3. To achieve call-by-reference in functions
4. For dynamic memory allocation (malloc, calloc)
5. To build data structures like linked lists, trees, graphs
Declaring and initializing pointers
Declaration
int *p; // p is a pointer to int Or in two steps:
float *q; // q is a pointer to float
int x = 10;
char *cptr; // cptr is a pointer to char
int *p; // declaration
The * next to the name tells the compiler this p = &x; // initialization
variable will hold an address of that type.
Initialization
Best practice is to point it to something valid: You should not use p before it is
int x = 10; initialized (that leads to undefined
int *p = &x; // p now stores address of x behavior).
Accessing a variable through its pointer
If:
Here
● & → “address of”
int x = 10;
int *p = &x;
● * → “value at address” (dereference)
Then:
Address Operator &
● p → address of x
● Used to obtain the memory address of a variable.
Example: p = &x;
● *p → value stored at that
Dereference Operator * address → which is 10
● Used to access the value at the address stored in a
pointer.
Example: value = *p
Pointer Example
Pointer Example 1. int x = 10;
○ x is 10.
2. int *p = &x;
○ p stores the address of x.
3. *p
○ Go to the address stored in p, fetch
the value there.
4. *p = 20;
○ Go to the address in p (which is x)
and store 20 there.
○ So x becomes 20.
This shows: changing *p actually changes x,
because p points to x.
Pointer Example
Pointers and arrays
int a[5] = {10, 20, 30, 40, 50};
Important facts:
1. a (array name) acts like a pointer to the first element.
○ So a is roughly equivalent to &a[0].
2. a[i] is the same as *(a + i).
Why?
So:
● a → address of a[0]
● *(a + 0) → a[0] → 10
● a + 1 → address of a[1]
● *(a + 1) → a[1] → 20
● a + 2 → address of a[2]
● and so on (this is called pointer arithmetic) ● *(a + 2) → a[2] → 30
Pointers and arrays
int a[4] = {10, 20, 30, 40};
int *p = a;
*p → value at 2000 → 10
Array (a): *(p+1) → value at 2004 → 20
Index Address Value
p++ → now p → 2004 → points to a[1]
---------------------------------------------
0 2000 --> 10
1 2004 --> 20
2 2008 --> 30
3 2012 --> 40
Pointer:
p ------> 2000 (points to a[0])
Now p points to a[0], and:
● *(p + 0) → 10
● *(p + 1) → 20
● *(p + 2) → 30 …
Write a C program to print 10, 20, 30 from the array
{10,20,30,40,50} using pointer notation and pointer
increment
In main():
Call by Reference Using x = 10
Pointers increase(&x); // &x = address of x
In function:
void increase(int *p)
● p receives the address of x
● *p means “value stored at that address”
● So *p = *p + 1; modifies x directly
Memory Understanding:
x = 10 (address: 5000)
p = 5000
*p = value at address 5000 → 10
*p = 10 + 1 → 11 (so x becomes 11)
Concept Meaning Operator Example
Pointer Stores memory address * (for dereference) int *p;
Address of variable Gives address & p = &x;
Dereference Access value at address * y = *p;
Array name Address of first element — p = a;
Pointer arithmetic Moves pointer by type size +, -, ++ p++;
What will this program print?
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() { int main() { int main() {
int x = 10; int x = 5; int a[3] = {4, 5, 6};
int *p = &x; int *p = &x; int *p = a;
printf("%d\n", *p); *p = 20; printf("%d %d %d", *p, *(p+1), *(p+2));
return 0; printf("x = %d\n", x); return 0;
} return 0; }
}
What will this program print? #include <stdio.h>
#include <stdio.h> #include <stdio.h> int main() {
int main() {
int main() { int a[3] = {4, 5, 6};
int x = 10; int *p = a;
int x = 5;
int *p = &x; printf("%d %d %d", *p, *(p+1), *(p+2));
int *p = &x;
printf("%d\n", *p); return 0;
*p = 20;
return 0; }
printf("x = %d\n", x);
} Ans: 4 5 6
return 0; a is the address of a[0]
Ans: x = 10
p = &x → pointer p stores the } p = a → p points to first element (4)
address of x
Ans: x = 20 *p → 4
*p means: go to that address p points to x
and get the value *p = 20; means: put 20 into *(p+1) → next element → 5
the memory location of x *(p+2) → next element → 6
Value stored inside x is 10, so *p
prints 10. So x becomes 20.
Pointer arithmetic automatically moves by size of int
What will this program print?
1) #include <stdio.h>
2)int x = 50;
int main() { int *p = &x;
int arr[] = {10, 20, 30, 40}; printf("%d", *p);
int *p = arr;
3) What does *(a+2) represent?
p++;
A. Address of a[2]
*p = 99; B. Value inside a[2]
for (int i = 0; i < 4; i++) { C. Value inside a[0]
D. Syntax error
printf("%d ", arr[i]);
} return 0;
}
What will this program print?
#include <stdio.h> int x = 50;
int main() { Initial array: {10, 20, 30, 40} int *p = &x;
printf("%d", *p);
int arr[] = {10, 20, 30, 40}; p = arr → points to arr[0]
int *p = arr; p++ → moves pointer to arr[1] Ans: 50
p++; *p = 99 → changed arr[1] to 99 What does *(a+2) represent?
*p = 99; So final array becomes: A. Address of a[2]
B. Value inside a[2]
for (int i = 0; i < 4; i++) { {10, 99, 30, 40}
C. Value inside a[0]
printf("%d ", arr[i]); D. Syntax error
} return 0;
}
What will this program print?
*(p + i) refers to: Writing int *p, x; means: What is incremented in pointer
arithmetic?
A. p[i] A. p and x are pointers
B. *p[i] B. Only p is pointer A. Address
C. &p[i] C. Only x is pointer B. Value
D. None D. Both are integers C. Variable
D. None
If int a[3]={1,2,3}; int *p=a; then
If p is NULL: Array name acts as:
*(p+1) is:
A. p stores zero A. Pointer to last element
A. 1
B. p stores garbage B. Pointer to first element
B. 2
C. Integer constant
C. Dereferencing allowed C. 3
D. Function pointer
D. p = address D. address
What will this program print?
*(p + i) refers to: Writing int *p, x; means: What is incremented in pointer
A. p[i] arithmetic?
A. p and x are pointers
B. *p[i] B. Only p is pointer A. Address
C. &p[i] C. Only x is pointer B. Value
D. None D. Both are integers C. Variable
D. None
If int a[3]={1,2,3}; int *p=a; then *(p+1)
If p is NULL: Array name acts as:
A. 1
A. p stores zero A. Pointer to last element B. 2
B. p stores garbage B. Pointer to first element C. 3
C. Dereferencing allowed C. Integer constant D. address
D. p = address D. Function pointer
Call by Value vs Call by Reference in C
Types of Pointers
1. Null pointer – points to nothing (int *p = NULL;)
2. Void pointer – generic pointer to any type
3. Wild pointer – uninitialized pointer (dangerous)
4. Dangling pointer – pointer pointing to freed memory
Function Modifying Array Using Pointer
Arrays passed to functions become pointers, so modifying them inside a function changes the original array.
File Management in C
● In C, a file represents a sequence of bytes stored on secondary memory (such as a
hard disk), managed using the standard library via the FILE structure.
● A file in C, uses a special pointer of type FILE * (a pointer to a structure defined in
<stdio.h>).
● This pointer manages all the information needed for the operating system to perform
I/O operations on the file, including:
a. The file's name and location.
b. The current read/write position (the file pointer).
c. The buffer used for transferring data.
Operations on Files
● Opening a file: You can open a file using the fopen() function, which takes two arguments: the name of
the file, and the mode in which you want to open the file (e.g., "r" for reading, "w" for writing, "a" for
appending, etc.).
● Creating a file: You can create a new file if file is not there by using the fopen() function.
● Reading from a file: Once a file is open, you can use various functions to read data from the file, such
as fgetc() to read a single character, fgets() to read a line of text, and fread() to read a block of data.
● Writing to a file: You can also use functions like fprintf() and fwrite() to write data to an open file.
● Moving the file pointer: The file pointer is a pointer that keeps track of the current position in the file.
You can use functions like fseek() and rewind() to move the file pointer to a different position in the file.
● Closing a file: Once you are done working with a file, it is important to close it using the fclose()
function. This ensures that any changes you made to the file are saved and any resources used by the file
are freed.
● Error handling: It's important to check for errors when working with files, such as when trying to open
a file that does not exist or when trying to read from a file that has reached the end of its data. You can
use the ferror() and feof() functions to check for errors and end-of-file conditions.
File Management in C
Two Main Types of Files:
1. Text files: These files contain plain text and can be opened and edited using a text editor.
Text files are stored with the ".txt" file extension and each line of text is separated by a
newline character. In C, the fprintf() and fscanf() functions are used to write and read text
files respectively.
2. Binary files: These files contain binary data and can't be opened and edited using a text
editor. Binary files are stored with the ".bin" file extension and there is no delimiter
between different data in the file. In C, the fwrite() and fread() functions are used to write
and read binary files respectively.
Text files are human-readable and easy to understand, while binary files are not human-readable
and only can be read and written by a program. It depends on the use case, you can choose which
type of file you want to use to store your data. A text file is suitable for storing a list of names and
addresses, while a binary file is suitable for storing an image or a video.
File Management in C
Syntax:
FILE *fptr; // fptr is the file pointer variable
FILE → a structure defined in <stdio.h>
fp → pointer to FILE
This pointer is used to perform all file operations.
File Management in C - Opening a File
Syntax:
A file is opened using the fopen() function.
Syntax:
fp = fopen("filename", "mode");
Example:
FILE *fp;
fp = fopen("[Link]", "w");
This opens (or creates) [Link] for writing.
Mode Meaning of Mode During Inexistence of file
File Management in C - Opening a File
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
w Open for writing. If the file exists, its contents are [Link] the file does not exist, it will be created.
wb Open for writing in binary mode. If the file exists, its contents are [Link] the file does not exist, it will be created.
a Open for [Link] to the end of the file. If the file does not exist, it will be created.
ab Open for append in binary [Link] to the end of the file. If the file does not exist, it will be created.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen() returns NULL.
w+ Open for both reading and writing. If the file exists, its contents are [Link] the file does not exist, it will be created.
wb+ Open for both reading and writing in binary mode. If the file exists, its contents are [Link] the file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exist, it will be created.
ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.
File Management in C - Closing a File
Always close a file after use using fclose().
Syntax:
fclose(fp);
Example:
fclose(fp); // file is closed
Closing a file:
● Releases memory
● Avoids corruption
● Ensures data is saved properly
● Closing files prevents memory leaks and can protect against data loss.
File Management in C - Writing to a File
fprintf() → write formatted data
fputs() → write string
fputc() → write a character
File Management in C - Reading to a File
fscanf() → read formatted data
fgets() → read string
fgetc() → read a character
File Management in C - Reading to a File
fscanf() → read formatted data
fgets() → read string
fgetc() → read a character
File Management in C - Reading to a File
File Management in C
WAP for writing some of the
characters (without taking input
from the keyboard) and
reading, printing , written
characters.