Module IV
Pointers in C
What is a Pointer?
A pointer is a variable that stores the memory address of another variable.
int i = 123;
int *p;
p = &i;
i is a normal integer variable.
p is a pointer to an integer (int *p).
&i gives the address of i, which is stored in p.
Why Use Pointers?
Efficient memory access and manipulation.
Enables dynamic memory allocation.
Useful for arrays and strings.
Essential for working with functions and structures.
Declaring a Pointer
datatype *pointer_name;
Examples:
int *p1; // pointer to int
float *p2; // pointer to float
char *p3; // pointer to char
#include <stdio.h>
int main()
{
int num = 10;
int *p1;
p1 = #
printf("Address of num = %p\n",p1); //%p format specifier is used to
//print the memory address of a variable
return 0;
}
Operators Used with Pointers
Operator Description
& Address of operator
* Dereferencing operator (value at addr)
Example:
int x = 20;
int *p = &x;
printf("%d", *p); // prints 20
Pointer Arithmetic
Pointers can be incremented or decremented.
int *p;
p++; // moves to the next integer address (usually +4 bytes)
Pointers and Arrays
The name of an array is a pointer to its first element.
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int *p;
p = arr;
printf("%p",p);
return 0;
}
✅Quick Summary
Pointers hold memory addresses.
* is used to dereference (access value).
& gets the address.
Useful for functions, arrays, strings, and dynamic memory
Q. Differentiate between address operator (&) and indirection (*) operator
Ref: Notes, Module 4 Part 1
Q. What do you mean by a pointer variable? How is it initialized?
Ref: Notes, Module 4 Part 1
Q. Write a C program to reverse a string using pointers
#include <stdio.h>
#include <string.h>
int main()
{
char str[50];
char *p;
int len;
printf("Enter a string: ");
gets(str);
p=str;
len = strlen(str);
printf("The reverse of the string is: ");
for (int i = len-1; i >= 0; i--)
{
printf("%c", *(p + i));// Print each character from
//the end to the beginning
}
return 0;
}
Q. Write a C program to print the elements of an array in reverse order using pointers.
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate array
//size
printf("Original array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
// Print in reverse order using pointers
printf("Reversed array: ");
int *ptr = arr + n - 1; // Point to the last element
while (ptr >= arr)
{
printf("%d ", *ptr);
ptr--; // Move pointer to the previous element
}
return 0;
}
Q. Write a C program to swap two numbers using pointers.
#include <stdio.h>
int main()
{
int a, b, temp;
int *p1, *p2;
// Input two numbers
printf("Enter two numbers:\n");
scanf("%d %d", &a, &b);
// Assign pointers
p1 = &a;
p2 = &b;
// Swapping using pointers
temp = *p1;
*p1 = *p2;
*p2 = temp;
// Output the result
printf("After swapping:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
Q. Differentiate between array of pointers and pointer to an array
Array of Pointers
An array of pointers is a collection where each element is a pointer (usually pointing to a
variable or another array).
int *arr[5];
Explanation:
arr is an array of 5 pointers to integers.
Each element arr[i] is a pointer to an int.
Example:
int a = 10, b = 20, c = 30;
int *arr[3] = { &a, &b, &c };
printf("%d", *arr[1]); // Output: 20
Pointer to an Array
A pointer to an array is a single pointer that points to an entire array.
int arr[5] = {1, 2, 3, 4, 5};
int (*ptr)[5] = &arr;
printf("%d", (*ptr)[2]); // Output: 3
Q. What is meant by the scale factor of a pointer variable? Explain using examples
Pointer Increments and Scale Factor in C
A pointer is a variable that stores the address of another variable.
int a = 10;
int *p = &a;
Here, p is a pointer to an integer, and it holds the address of variable a.
Pointer Increments
When a pointer is incremented using ptr++, it moves to the next memory location of its
type — not just by 1 byte.
Example:
int arr[] = {10, 20, 30};
int *ptr = arr;
ptr++; // Moves to the next integer in the array
Even though you write ptr++, internally the pointer increases by a value based on the size of
the type it points to.
Scale Factor (Size of Data Type)
The scale factor is the size (in bytes) of the data type that the pointer points to.
This is used internally when incrementing or decrementing a pointer.
Data Type Size (Typical 32-bit System) Meaning of ptr++
char 1 byte ptr increases by 1 byte
int 4 bytes ptr increases by 4 bytes
float 4 bytes ptr increases by 4 bytes
double 8 bytes ptr increases by 8 bytes
Q. Differentiate between address operator (&) and indirection (*) operator
Ref: Notes, Module 4 Part 1
Q. What do you mean by a pointer variable? How is it initialized?
Ref: Notes, Module 4 Part 1
Q. Write a C program to reverse a string using pointers
#include <stdio.h>
#include <string.h>
int main()
{
char str[50];
char *p;
int len;
printf("Enter a string: ");
gets(str);
p=str;
len = strlen(str);
printf("The reverse of the string is: ");
for (int i = len-1; i >= 0; i--)
{
printf("%c", *(p + i));// Print each character from
//the end to the beginning
}
return 0;
}
Q. Write a C program to print the elements of an array in reverse order using pointers.
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate array
//size
printf("Original array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
// Print in reverse order using pointers
printf("Reversed array: ");
int *ptr = arr + n - 1; // Point to the last element
while (ptr >= arr)
{
printf("%d ", *ptr);
ptr--; // Move pointer to the previous element
}
return 0;
}
Q. Write a C program to swap two numbers using pointers.
#include <stdio.h>
int main()
{
int a, b, temp;
int *p1, *p2;
// Input two numbers
printf("Enter two numbers:\n");
scanf("%d %d", &a, &b);
// Assign pointers
p1 = &a;
p2 = &b;
// Swapping using pointers
temp = *p1;
*p1 = *p2;
*p2 = temp;
// Output the result
printf("After swapping:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
Q. Differentiate between array of pointers and pointer to an array
Array of Pointers
An array of pointers is a collection where each element is a pointer (usually pointing to a
variable or another array).
int *arr[5];
Explanation:
arr is an array of 5 pointers to integers.
Each element arr[i] is a pointer to an int.
Example:
int a = 10, b = 20, c = 30;
int *arr[3] = { &a, &b, &c };
printf("%d", *arr[1]); // Output: 20
Pointer to an Array
A pointer to an array is a single pointer that points to an entire array.
int arr[5] = {1, 2, 3, 4, 5};
int (*ptr)[5] = &arr;
printf("%d", (*ptr)[2]); // Output: 3
Q. What is meant by the scale factor of a pointer variable? Explain using examples
Pointer Increments and Scale Factor in C
A pointer is a variable that stores the address of another variable.
int a = 10;
int *p = &a;
Here, p is a pointer to an integer, and it holds the address of variable a.
Pointer Increments
When a pointer is incremented using ptr++, it moves to the next memory location of its
type — not just by 1 byte.
Example:
int arr[] = {10, 20, 30};
int *ptr = arr;
ptr++; // Moves to the next integer in the array
Even though you write ptr++, internally the pointer increases by a value based on the size of
the type it points to.
Scale Factor (Size of Data Type)
The scale factor is the size (in bytes) of the data type that the pointer points to.
This is used internally when incrementing or decrementing a pointer.
Data Type Size (Typical 32-bit System) Meaning of ptr++
char 1 byte ptr increases by 1 byte
int 4 bytes ptr increases by 4 bytes
float 4 bytes ptr increases by 4 bytes
double 8 bytes ptr increases by 8 bytes
Passing Pointers to Functions in C (Call by Reference)
Passing pointers to functions in C refers to the process of providing the address of a
variable (instead of its value) as an argument to a function. This allows the function to
access and modify the original variable directly, enabling call by reference behavior.
Why Pass Pointers to a Function?
Passing pointers allows:
Direct modification of variables in the calling function (i.e., call by reference).
Efficient data handling, especially for large structures or arrays.
Syntax
void function_name(datatype *pointer_variable);
Example: Swap Two Numbers Using Pointers
#include <stdio.h>
// Function that takes two integer pointers
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x = 10, y = 20;
printf("Before Swap: x = %d, y = %d\n", x, y);
// Passing addresses of x and y
swap(&x, &y);
printf("After Swap: x = %d, y = %d\n", x, y);
return 0;
}
Explanation
swap takes pointers to int as arguments: int *a, int *b.
&x and &y pass the addresses of x and y to the function.
Inside swap, *a and *b access and modify the values directly in memory.
Key Points
Pointer parameters allow functions to modify actual arguments.
Especially useful for swapping, dynamic memory, returning multiple values, etc.
Always ensure proper dereferencing of pointers when used.
Previous Year Questions:
1. Explain how pointers can be passed to functions in C.
2. What is meant by passing arguments into a function by reference? Write a program to swap
two numbers using pass by reference.
Pointer to Structure in C
What is a Structure?
A structure in C is a user-defined data type that allows grouping variables of different types
under a single name.
struct Student
{
int id;
char name[20];
float marks;
};
Pointer to Structure
A pointer to a structure is a pointer variable that holds the address of a structure variable.
Syntax:
struct StructureName *pointerName;
Example:
struct Student s1;
struct Student *ptr;
ptr = &s1;
Here, ptr is a pointer to a Student structure and stores the address of s1.
Accessing Structure Members Using Pointer
We use the arrow operator (->) to access members of a structure through a pointer.
Syntax:
pointerName->memberName;
Example:
#include <stdio.h>
struct Student {
int id;
char name[20];
float marks;
};
int main() {
struct Student s1 = {101, "Alice", 92.5};
struct Student *ptr;
ptr = &s1;
// Accessing members using pointer
printf("ID: %d\n", ptr->id);
printf("Name: %s\n", ptr->name);
printf("Marks: %.2f\n", ptr->marks);
return 0;
}
Output:
ID: 101
Name: Alice
Marks: 92.50
Modifying Structure Members Using Pointer
You can also change the values of structure members using a pointer.
Example:
ptr->marks = 95.0; // Updates marks to 95
Summary
Concept Explanation
Holds address of a structure
Pointer to structure
variable
Access operator -> used instead of .
Declaration struct Student *ptr;
Initialization ptr = &s1;
Member access ptr->id, ptr->name
Pointer to Pointer (Double Pointer)
What is a Pointer to Pointer?
In C, a pointer to a pointer is a variable that stores the address of another pointer variable.
It’s also called a double pointer.
Syntax:
int **ptr;
Here, ptr is a pointer to another pointer to an integer.
Why Use Pointer to Pointer?
To modify the value of a pointer in a function.
To handle multi-dimensional arrays.
Used in dynamic memory allocation of arrays of pointers.
For returning a pointer from a function using pass-by-reference.
Declaration Example
int a = 10;
int *p = &a; // Pointer to int
int **pp = &p; // Pointer to pointer to int
Memory Representation:
Let's assume:
a = 10
p contains the address of a (say 0x100)
pp contains the address of p (say 0x200)
Variable Value Meaning
a 10 Actual integer value
p 0x100 Address of a
*p 10 Value stored at address in p
pp 0x200 Address of p
*pp 0x100 Value stored at pp (i.e., p)
**pp 10 Final dereference to get value
Example program :
#include <stdio.h>
int main()
{
int a = 10;
int *p1;
p1 = &a;
printf("a = %d\n",a); //Value of a
printf("&a = %d\n",&a); // Address of a
printf("p1 = %d\n",p1); // Value stored in p1 (i.e., address of a)
printf("&p1 = %d\n",&p1); // Address of p1 itself
printf("*p1 = %d\n",*p1); //Value at address stored in p1(value of a)
int **p2;// Double pointer
p2 = &p1;// p2 stores address of p1
printf("p2 = %d\n",p2);// Address stored in p2 (i.e., address of p1)
printf("*p2 = %d\n",*p2);//Value @ adrs stored in p2(value of p1, addr. of a)
printf("**p2 = %d\n",**p2); // Final dereference to get value of a
return 0;
}
Dynamic Memory Allocation in C
Static Memory Allocation
Definition: Memory is allocated at compile-time.
Memory Size: Fixed — you must know the size in advance.
Allocated By: Compiler.
Lifetime: Exists throughout the program’s lifetime.
Speed: Faster since allocation happens once at compile-time.
What is Dynamic Memory Allocation?
Dynamic memory allocation in C allows programmers to allocate memory during runtime,
using pointers. This is useful when the amount of memory required is not known at compile
time.
Why Use It?
Efficient memory usage.
Allocate memory as needed.
Create data structures like arrays, linked lists, trees, etc., dynamically.
� Functions Used for Dynamic Memory Allocation
Function Description
malloc() Allocates specified bytes and returns a void pointer
calloc() Allocates memory for a block of data, initializes all bytes to zero
realloc() Reallocates memory to resize previously allocated memory
free() Frees dynamically allocated memory
What is malloc()?
malloc() stands for memory allocation.
It is used to dynamically allocate memory at runtime from the heap.
Syntax:
pointer = (data_type *)malloc(number_of_bytes);
It returns a pointer to the first byte of the allocated memory block.
Basic Example Using malloc()
� Program to Allocate Memory for n Integers and Store User Input
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
// Allocate memory for n integers
arr = (int *)malloc(n * sizeof(int));
// Check if memory allocation was successful
if (arr == NULL)
{
printf("Memory allocation failed!\n");
return 1;
}
// Read values into the dynamically allocated array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", arr+i);
}
// Display the values
printf("You entered: ");
for (int i = 0; i < n; i++)
{
printf("%d ", *(arr+i));
}
// Free the allocated memory
free(arr);
return 0;
}
Dynamic Memory Allocation
Definition: Memory is allocated at run-time.
Memory Size: Can be determined during program execution.
Allocated By: Programmer using library functions.
Lifetime: Until you explicitly free the memory.
Speed: Slower than static allocation due to run-time processing.
File Handling in C
1. Different Types of Files in C
C supports two main types of files:
� a) Text Files
Human-readable (ASCII format : Characters).
Data is stored as plain text lines.
Can be opened in editors like Notepad.
Slower and larger in size.
� b) Binary Files
A binary file is a file that stores data in the same format as it is stored in computer
memory — raw bytes, not plain text. Unlike text files ,binary files are not human-
readable.
Machine-readable (binary format).
Faster and compact.
Not human-readable.
� 2. Opening and Closing a File
� fopen() – To Open a File
Syntax:
FILE *fp;
fp = fopen("filename.txt", "mode");
FILE *fp; is a file pointer declaration.
FILE is a structure in C defined in the header file stdio.h.
It is used to hold information about a file — like its name, status (open/closed), current
position in the file, etc.
*fp means you're creating a pointer to a FILE structure — this pointer is used to handle
file operations like reading, writing, and closing.
� Modes in fopen()
Mode Meaning
"r" Read (file must exist)
"w" Write (creates new or overwrites)
"a" Append (creates new or adds to end)
"r+" Read and write (file must exist)
"w+" Write and read (new or overwrite)
"a+" Append and read
"rb" Read binary
"wb" Write binary
"ab" Append binary
� fclose() – To Close a File
Syntax:
fclose(fp);
Always close files to free resources.
� 3. Writing to and Reading from a File
� Writing Text
FILE *fp = fopen("text.txt", "w");
fprintf(fp, "Hello, world!");
fclose(fp);
� Reading Text
FILE *fp = fopen("text.txt", "r");
char buffer[100];
fgets(buffer, 100, fp);
printf("%s", buffer);
fclose(fp);
Program: Open a File in C
#include <stdio.h>
int main()
{
FILE *fp;
// Open the file in read mode
fp = fopen("example.txt", "r");
// Check if the file exists and opened successfully
if (fp == NULL)
{
printf("Error: Could not open the file.\n");
} else {
printf("File opened successfully.\n");
// Close the file after use
fclose(fp);
}
return 0;
}
Explanation:
FILE *fp; declares a file pointer.
fopen("example.txt", "r"); tries to open a file named example.txt in read mode.
if (fp == NULL) checks whether the file exists and was opened successfully.
fclose(fp); closes the file to free up resources.
You can change the mode to:
"w" to open for writing
"a" to open for appending
"rb", "wb", "ab" for binary modes
Q.Write a C program to count number of lines in a text file.
#include <stdio.h>
int main()
{
FILE *file;
int lines = 0;
char ch;
// Open file in read mode
file = fopen("text.txt", "r");
// Count lines by counting '\n'
while ((ch = fgetc(file)) != EOF)
{
if (ch == '\n')
{
lines++;
}
}
// Close file
fclose(file);
// Print result
printf("The file has %d lines.\n", lines);
return 0;
}
Q. Write a c program to count number of vowels in a file
#include <stdio.h>
int main()
{
FILE *file;
int vowels = 0;
char ch;
// Open file in read mode
file = fopen("text.txt", "r");
// Count lines by counting '\n'
while ((ch = fgetc(file)) != EOF)
{
if (ch == 'a'||ch == 'e'||ch == 'i'||ch == 'o'||
ch =='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
{
vowels++;
}
}
fclose(file);
// Print result
printf("The file has %d vowels.\n", vowels);
return 0;
}
Q. Write a C program to replace vowels in a text file with
character ‘x’
#include <stdio.h>
int main()
{
FILE *file;
char ch;
// Open the file in read+write mode
file = fopen("text.txt", "r+");
if (file == NULL)
{
printf("Error opening file.\n");
return 1;
}
while ((ch = fgetc(file)) != EOF)
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o'
|| ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O'
|| ch == 'U')
{
// Move file pointer back to overwrite the vowel
fseek(file, -1, SEEK_CUR);
fputc('x', file);
fseek(file, 0, SEEK_CUR);
}
}
fclose(file);
return 0;
}
Q. Write a c program to copy the contents of a file into
another
#include <stdio.h>
int main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("text_1.txt", "r");
fp2 = fopen("text_2.txt", "w");
// Copy contents character by character
while ((ch = fgetc(fp1)) != EOF)
{
fputc(ch, fp2);
}
printf("File copied successfully.\n");
fclose(fp1);
fclose(fp2);
return 0;
}
Q. Write a C program to read data in a given file and display
the file content on console.
Ref: previous notes
Library functions related to file
1. fseek()
Purpose: Moves the file pointer to a specific location within a file.
Syntax:
int fseek(FILE *fp, long offset, int origin);
Parameters:
o fp: File pointer.
o offset: Number of bytes to move the pointer.
o origin: Starting point (SEEK_SET, SEEK_CUR, SEEK_END).
Returns: 0 if successful, non-zero on error.
Example:
FILE *fp = fopen("file.txt", "r");
fseek(fp, 10, SEEK_SET); // Move 10 bytes from the beginning
fclose(fp);
2. ftell()
Purpose: Returns the current position of the file pointer.
Syntax:
long ftell(FILE *fp);
Parameters:
o fp: File pointer.
Returns: Current file position in bytes, or -1 on error.
Example:
FILE *fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
long size = ftell(fp); // Get file size
fclose(fp);
printf("File size: %ld bytes\n", size);
3. fread()
Purpose: Reads data from a file into memory (used for binary files).
Syntax:
size_t fread(void *ptr, size_t size, size_t count, FILE *fp);
Parameters:
o ptr: Pointer to memory where data will be stored.
o size: Size of each element to read.
o count: Number of elements.
o fp:
File pointer.
Returns: Number of elements successfully read.
Example:
FILE *fp = fopen("data.bin", "rb");
int arr[5];
fread(arr, sizeof(int), 5, fp);
fclose(fp);
4. fwrite()
Purpose: Writes data from memory to a file (used for binary files).
Syntax:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);
Parameters:
o ptr: Pointer to the data to write.
o size: Size of each element to write.
o count: Number of elements.
o fp: File pointer.
Returns: Number of elements successfully written.
Example:
FILE *fp = fopen("data.bin", "wb");
int arr[5] = {1, 2, 3, 4, 5};
fwrite(arr, sizeof(int), 5, fp);
fclose(fp);
Q. Write a C Program to read a file and replace all vowels with *
#include <stdio.h>
int main()
{
FILE *fp = fopen("text.txt", "r+"); // Open file for read/write
if (fp == NULL)
{
printf("Cannot open file.\n");
return 1;
}
char ch;
long pos;
while ((ch = fgetc(fp)) != EOF)
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o'
|| ch == 'u'|| ch == 'A' || ch == 'E' ||
ch == 'I' || ch == 'O' || ch == 'U')
{
// Move the file pointer back by one to overwrite the
vowel
pos = ftell(fp);
fseek(fp, pos - 1, SEEK_SET);
fputc('*', fp);
fseek(fp,pos,SEEK_SET);
}
}
fclose(fp);
printf("All vowels replaced with '*'.\n");
return 0;
}