Unit 5
Unit 5
Unit-V
Pointers, Dynamic Memory Allocation, File Management in C, Pointer Variable and
its importance, Pointer Arithmetic, Passing parameters by reference, Pointer to
Pointer, Pointer to Functions, Dangling Pointer, Console input output functions, Disk
Input Output Functions, Opening, closing, and Creating Data Files.
Assessment and Evaluation Plan
2. Untyped Pointers:-
Untyped Pointers means a pointer can points to any type of data. This is also
called Generic Pointer in a C language.
Eg:- Void pointer is called a Generic pointer that can points to any type of data.
Generally, in pointers concept whatever the operations we do, we need to take the
help of only two operators:-
2) Pointer Operator (*) :- Pointer variable returns the value which is inside a
specified address.
Simple Example Based on Pointers
#include<stdio.h> i i variable
void main() {
Initial Value
int i=100; 100
Memory
int* ptr; 2046 Location of i
ptr= &i;
variable
printf(“%d”, i);---------100
printf(“%d”, ptr);---------2046
*
ptr is a pointer
printf(“%d”, &i);---------2046 ptr variable
printf(“%d”, &ptr);---------3002
printf(“%d”, *ptr);---------100 2046
printf(“%d”, *(&i));---------100
}
3002
Memory Location of
ptr Variable
In implementation of Pointers
Example
Expression What it means Format specifier
Output
i Value of integer %d 100
Value pointed
*ptr %d 100
to
Address stored
ptr %p + (void*) 0x7ffee4c8a6ac
in pointer
Address of
&i %p + (void*) 0x7ffee4c8a6ac
variable i
Address of
&ptr %p + (void*) 0x7ffee4c8a6b0
pointer variable
Importance of Pointers
#include <stdio.h>
int main() {
int var = 20; // actual variable
declaration
OUTPUT
int *ip; // pointer variable declaration
return 0;
Null Pointers
It is always a good practice to assign a NULL value to a pointer variable in case
you do not have an exact address to be assigned.
This is done at the time of variable declaration. A pointer that is assigned NULL is
called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard
libraries.
OUTPUT
Pointer Arithmetic
Let us consider that ptr is an integer pointer which points to the address 1000.
Assuming 32-bit integers, let us perform the following arithmetic operation on the
pointer:-
ptr++;
After the above operation, the ptr will point to the location 1004 because each
time ptr is incremented, it will point to the next integer location which is 4 bytes
next to the current location.
This operation will move the pointer to the next memory location without
impacting the actual value at the memory location.
Program to demonstrate the concept of incrementing a pointer
#include <stdio.h>
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
OUTPUT
/* let us have array address in pointer */
ptr = var;
return 0;
}
Pointer to Pointer
OUTPUT
Poll/Quiz
a) int *px;
b) float a, b;
c) float a= -0.167;
This is done using a set of functions provided in the stdlib.h library. The key
functions are:
1. Malloc
Allocates a specified number of bytes of memory and returns a pointer to the first
byte.
int *ptr;
ptr = (int *)malloc(sizeof(int) * 5); // Allocates memory for 5 integers
if (ptr == NULL) {
printf("Memory allocation failed\n");
exit(1); // Exit the program if allocation fails
}
Dynamic Memory Allocation
2. Calloc
if (ptr == NULL) {
printf("Memory allocation failed\n");
exit(1); // Exit the program if allocation fails
}
Dynamic Memory Allocation
3. realloc()
Resizes the previously allocated memory block. It can also be used to
shrink or expand the allocated memory.
int *ptr;
ptr = (int *)malloc(sizeof(int) * 5); // Initially allocate memory for 5
integers
if (ptr == NULL) {
printf("Memory reallocation failed\n");
exit(1); // Exit the program if reallocation fails
}
Dynamic Memory Allocation
4. free()
Deallocates the dynamically allocated memory, ensuring there are no memory leaks.
c
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n, i;
. printf("Enter the number of elements: ");
c scanf("%d", &n);
if (ptr == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
// Input values
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}
// Output values
printf("You entered the elements:\n");
for (i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
A dangling pointer is a pointer that continues to point to a memory location after the memory it
points to has been deallocated (freed). Accessing a dangling pointer can lead to undefined behavior,
such as program crashes or unexpected results.
. #include <stdio.h>
c
#include <stdlib.h>
void danglingExample() {
int *ptr = (int *)malloc(sizeof(int)); // Dynamically allocate
memory
*ptr = 100; // Assign value to the allocated memory
int main() {
danglingExample();
Outcomes of Today’s Lecture
When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter
them all.
However, if you have a file containing all the data, you can easily access
the contents of the file using a few commands in C.
You can easily move your data from one computer to another without any
changes.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files:-
Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain
text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the
least security and takes bigger storage space.
2. Binary files:-
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and
1's).
They can hold a higher amount of data, are not readable easily, and provides
better security than text files.
C File Operations
The file is opened using fopen() function, while opening you can
use any of the following mode as per the requirement.
Mode “r”: It is a read only mode, which means if the file is
opened in r mode, it won’t allow you to write and modify content
of it. When fopen() opens a file successfully then it returns the
address of first character of the file, otherwise it returns NULL.
Cont…..
To read the file, we must open it first using any of the mode, for
example if you only want to read the file then open it in “r”
mode. Based on the mode selected during file opening, we are
allowed to perform certain operations on the file.
fgetc( ): This function reads the character from current pointer’s
position and upon successful read moves the pointer to next
character in the file. Once the pointers reaches to the end of the
file, this function returns EOF (End of File). We have used EOF in
our program to determine the end of the file.
Writing to a File
To write the file, we must open the file in a mode that supports
writing. For example, if you open a file in “r” mode, you won’t be
able to write the file as “r” is read only mode that only allows
reading.
Closing a File
fclose(fp);
The fclose( ) function is used for closing an opened file. As an
argument you must provide a pointer to the file that you want to
close.
Example 1: Write to a text file
Example 1: Write to a text file
This program takes a number from the user and stores in the
file program.txt.
After you compile and run this program, you can see a text
file program.txt created in C drive of your computer.
When you open the file, you can see the integer you entered.
Example 2: Read from a text file
Example 2: Read from a text file
This program reads the integer present in the program.txt file and prints it
onto the screen.
If you successfully created the file from Example 1, running this program
will get you the integer you entered.
Other functions like fgetchar(), fputc() etc. can be used in a similar way.
Poll/Quiz
Q1. What is a file? Explain how the file open and file close functions.