0% found this document useful (0 votes)
2 views51 pages

Unit 5

The document outlines the syllabus for an 'Introduction to C Programming' course, focusing on pointers, dynamic memory allocation, and file management in C. It details assessment methods, lecture outcomes, and key concepts such as pointer types, arithmetic, and file handling operations. Additionally, it includes practical examples and explanations of dynamic memory allocation functions like malloc and calloc.

Uploaded by

2024a2r019
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views51 pages

Unit 5

The document outlines the syllabus for an 'Introduction to C Programming' course, focusing on pointers, dynamic memory allocation, and file management in C. It details assessment methods, lecture outcomes, and key concepts such as pointer types, arithmetic, and file handling operations. Additionally, it includes practical examples and explanations of dynamic memory allocation functions like malloc and calloc.

Uploaded by

2024a2r019
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Course Name: Introduction to C Programming

Course Code: COM-201

Faculty: Dr. Mehak Mengi


Assistant Professor
Dept. of CSE, MIET

Model Institute of Engineering & Technology


Unit 5 Syllabus

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

Assessment Tools Evaluation


✔ Sessionals Internal Assessment= 50
✔ Assignments ✔ Sessional-1= 10
✔ Quiz ✔ Sessional-2= 10
✔ Flipped Classrooms ✔ Assignment-1= 10
✔ Tutorial Sheets ✔ Assignment-2= 10
✔ Case Study ✔ Attendance = 10
External Marks= 100
Outcomes of Today’s Lecture

What are Pointers in C and its types?


Operators used in Pointers.
Importance of pointers.
Null pointer, Pointer Arithmetic and Pointer to Pointer concept.
C programs based on various pointer concepts.
Pointers in C

▪ Pointers are another important feature of C Language.


▪ A pointer is a variable which holds the memory address of another variable.
▪ Pointer points to a memory location.
▪ Pointer used to excess the information of a particular memory location.

Declaration of Variables To Declaration of Pointers


Convert
Data-type variable- name; the Data-type* variable- name;
variable eg.:- int* a; or int *a;
eg.:- int a; syntax to
Both the syntax are allowed in C.
pointer
just you
Either you can place asterisk *
can add symbol in front of a variable or
asterisk * you can place followed by the
datatype.
Types of Pointers in C

▪ Two types of pointers in C:


1.Typed Pointers:-
Typed Pointers means a pointer always points to a specific type of data.
Eg:- If you take integer pointer, it can points to only integer data.

int*……………………points to only integer data.


Eg:- If you take double pointer, it can points to only double data.

double*……………….points to only double data.


Eg:- If it is a struct employee pointer, it can points to only employee data.

Struct Emp*……...points to only Employee data.


Integer pointer cannot points to double data, double pointer cannot points to
structure data and structure pointer cannot points to integer data.
Cont….

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.

void*…………………points to any type of data.


Operators Used In Pointers

Generally, in pointers concept whatever the operations we do, we need to take the
help of only two operators:-

1) Address operator (&):- Address operator returns the address of a particular


variable. Memory location of a variable that what you specified that it will
return.

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

Pointer reduces the code and improves the performance.


It is used to retrieving strings, trees, etc. and used with arrays, structures, and
functions.
We can return multiple values from a function using the pointer.
It makes you able to access any memory location in the computer's memory.
There are many applications of pointers in c language:-
1) Dynamic memory allocation
 In c language, we can dynamically allocate memory using malloc() and calloc()
functions where the pointer is used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It
reduces the code and improves the performance.
Program which Prints the Address of the Variables Defined

printf("Address of var1 variable: %p\n",


(void*)&var1);
printf("Address of var2 variable: %p\n",
(void*)&var2);
OUTPUT
Program to demonstrate How to Use Pointers in C

#include <stdio.h>

int main() {
int var = 20; // actual variable
declaration
OUTPUT
int *ip; // pointer variable declaration

ip = &var; // store address of var in


pointer variable

// Use %p for printing addresses (standard


format)
printf("Address of var variable: %p\n",
(void*)&var);
printf("Address stored in ip variable: %p\n",
(void*)ip);
printf("Value of *ip variable: %d\n", *ip);

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>

const int MAX = 3;

int main () {
int var[] = {10, 100, 200};
int i, *ptr;
OUTPUT
/* let us have array address in pointer */
ptr = var;

for (i = 0; i < MAX; i++) {


printf("Address of var[%d] = %p\n", i, (void
*)ptr);
printf("Value of var[%d] = %d\n", i, *ptr);

/* move to the next location */


ptr++;
}

return 0;
}
Pointer to Pointer

A pointer to a pointer is a form of multiple indirection, or a chain of pointers.


Normally, a pointer contains the address of a variable. When we define a pointer
to a pointer, the first pointer contains the address of the second pointer, which
points to the location that contains the actual value as shown below:-

A variable that is a pointer to a pointer must be declared as such. This is done by


placing an additional asterisk in front of its name.
For example, the following declaration declares a pointer to a pointer of type int −
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing
that value requires that the asterisk operator be applied twice.
Program to demonstrate the concept of pointer to pointer

OUTPUT
Poll/Quiz

Google Form link for quiz on Pointers in C -


Practice Questions

Q1. Explain the meaning of each of the following declarations:-

a) int *px;

b) float a, b;

float *pa, *pb;

c) float a= -0.167;

float *pa= &a;

d) Char c1, c2, c3;

char *pc1, *pc2, *pc3= &c1;


Summarize the Lecture

In Today’s Lecture we discussed about :-


Pointers in C.
Types of pointers in C.
Operators used in pointers.
Importance of pointers.
Null pointers.
Pointer Arithmetic.
Pointer to Pointer.
C programs based on various pointers concepts.
Questions- Related to Topic

Q1. Explain the use of pointer with suitable program.

Q2. How is pointer declared? How is variable accessed through pointers?


Explain the role of pointers with the help of example.

Q3. What is pointer? How it is declared and initialized? Explain with


suitable example.
Dynamic Memory Allocation

Dynamic memory allocation in C is a process of allocating memory at runtime


using pointers.

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.


2.calloc() – Allocates memory for an array of specified elements, initializing all
bytes to zero.
3.realloc() – Resizes previously allocated memory.
4.free() – Deallocates previously allocated memory.
Dynamic Memory Allocation

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

Allocates memory for an array of elements, initializing all elements to zero.


int *ptr;
ptr = (int *)calloc(5, sizeof(int)); // Allocates memory for 5 integers, each
initialized to 0

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

// Resize memory to hold 10 integers


ptr = (int *)realloc(ptr, sizeof(int) * 10);

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

free(ptr); // Free the memory when it is no longer needed


ptr = NULL; // Set pointer to NULL after freeing
Example of Dynamic Memory Allocation using Pointers

#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n, i;
. printf("Enter the number of elements: ");
c scanf("%d", &n);

// Dynamically allocate memory for n integers


ptr = (int *)malloc(n * sizeof(int));

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]);
}

// Free the allocated memory


free(ptr);
return 0;
}
Dangling Pointers

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

free(ptr); // Free the allocated memory

printf("Value after free: %d\n", *ptr); // Undefined


behavior - ptr is now a dangling pointer
}

int main() {
danglingExample();
Outcomes of Today’s Lecture

 C File Handling and Why Files are needed?


 Types of Files, C File operations and various file opening modes.
 How to open, read, write and close a file?
 Justify the use of file manipulation operations.
 C programs to read and write in a file.
C File Handling

 A file is a container in computer storage devices used for storing


data.
 A file represents a sequence of bytes, regardless of it being a
text file or a binary file.
 C programming language provides access on high level functions
as well as low level (OS level) calls to handle file on your storage
devices.
Why Files are Needed?

 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

 Different operations that can be performed on a file are:


 Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
 Opening an existing file (fopen)
 Reading from file (fscanf or fgets)
 Writing to a file (fprintf or fputs)
 Moving to a specific location in a file (fseek, rewind)
 Closing a file (fclose)
 The text in the brackets denotes the functions used for performing those
operations.
Functions in File Operations
Opening a File

 fopen() function is used for opening a file.


 Syntax:
 FILE pointer_name = fopen ("file_name", "Mode");
 pointer_name can be anything of your choice.
 file_name is the name of the file, which you want to open. Specify the full path
here like “C:\\myfiles\\newfile.txt”.
 While opening a file, you need to specify the mode. The mode that we use to read
a file is “r” which is “read only mode”.
Various File Opening Modes

 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…..

 Mode “w”: It is a write only mode. The fopen() function creates a


new file when the specified file doesn’t exist and if it fails to
open file then it returns NULL.
 Mode “a”: Using this mode Content can be appended at the end
of an existing file. Like Mode “w”, fopen() creates a new file if it
file doesn’t exist. On unsuccessful open it returns NULL.
 File Pointer points to: last character of the file.
Cont…..
Reading a File

 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

 Google Form link for quiz on Data Files-


Summarize the Lecture

 In Today’s Lecture we discussed about :-


 C File Handling.
 Why files are needed?
 Types of files.
 C file operations.
 Functions in File Operations.
 Various file opening modes.
 Examples of C programs based on Data files.
Questions- Related to Topic

Q1. What is a file? Explain how the file open and file close functions.

Q2. Describe various modes of opening and closing of a data file in C.

Q3. Write a program to read a file, count number of lines, number of


words, number of characters and white spaces till the end of file is
encountered.
Thank You
Thank You

You might also like