This document provides details about memory system and file handling in C.
C language basics is given in this document and helps learner to understand.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0 ratings0% found this document useful (0 votes)
6 views27 pages
PPS Unit 5
This document provides details about memory system and file handling in C.
C language basics is given in this document and helps learner to understand.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 27
Unit-5:
Pointers: Introduction, Declaration, Applications, Introduction to Dynamic Memo
Allocation (Malloc, Calloc, Realloc, Free), String and String functions , Use of Pointe:
lin Self-Referential Structures, Notion of Linked List (No Implementation)
[File Handling: File I/O Functions, Standard C Preprocessors, Defining and Calli
[Macros and Command-Line Arguments.UNIT-V
POINTERS:
One of the powerful features of C is ability to access the memoi
memory address. Thi
of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say that
pointer points to a variable that is stored at that address. A pointer itself usually occupies 4
bytes of memory (then it can address cells from 0 to 232-1).
variables by their
san be done by using Pointers. The real power of C lies in the proper use
Advantages of Pointers:
1 A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
They increase the execution speed.
4.
A variable that holds a physical memory address is called a pointer variable or Pointer.
Declaration :
Datatype * Variable-name;
Eg: int “ad; /* pointer to int */
char *5; /* pointer to char */
float *fp; 7* pointer to float */
/* pointer to variable that is a pointer to char */
A pointer is a variable that contains an address which is a location of another variable in
memory.
Consider the Statement
pedi;Here *&’ is called address of a variable.
‘p’ contains the address of a variable i.
‘The operator & returns the memory address of variable on which it is operated, this is
called Referencing,
The * operator is called an indirection operator or dereferencing operator which is used to
display the contents of the Pointer Variable.
Consider the following Statements
int *p.xs
Assume that x is stored at the memory address 2000. Then the output for the following
printf statements is :
Output
Printf(“The Value of x is %d",x); 5
Printf(“The Address of x is %u",&x); 2000
Printf(“The Address of x is %u",p); 2000
Printf(“The Value of x is %d",*p); 5
Printf(“The Value of x is %d",*(8&x)); 5
POINTERS WITH ARRAYS :
When an array is declared, elements of array are stored in contiguous locations, The
address of the first element of an array is called its base address.
Consider the array
2000 200220042006 2008
af) al] a2] a3] af]
‘The name of the array is called its base address.
i.e., aand k& a[20] are equal.
Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then we can
‘make the pointer P to point to the array a by following assignmentPou;
We can access every value of array a by moving P from one element to another.
ie, P points to 0" element
P+i points to 1“ element
pa points to 2 element
P43. points to 3" element
P44 points to 4" element
Reading and Printing an array using Pointers :
main(
(
int Mais
printi(“Enter five elements
for (i=0;i<5;i++)
scant(“%d" a
prinu(“The array elements are:");
for (i=O;i<5si++)
printi%d", "(a+
}
In one dimensional array, afi] element is referred by
(ai) is the address of i” element,
*® (asi) is the value at the i" element,
In two-dimensional array, afi|j] element is represented as
*CMari) jyDynamic memory allocation
The concept of dynamic memory allocation in ¢ language enables the C programmer to
allocate memory at runtime. Dynamic memory allocation in c language is possible by
4 functions of stdlib.h header file.
malloe()
calloc()
realloc()
free()
Fen
Before learning above functions, let’s understand the difference between static memory
allocation and dynamic memory allocation.
static memory allocation dynamic memory allocation
memory is allocated at compile time. memory is allocated at run time.
memory can’t be increased while memory can be increased while
executing program. executing program
used in array. used in linked list.
Now let’s have a quick look at the methods used for dynamic memory allocation.Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer first
byte of allocated space
calloc() Allocates space for an array elements, initializes to zero and
then returns a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space
malloc() function in C
The malloc() function allocates single block of requested memory.
It doesn’t initialize memory at execution time, so it has garbage value initially.
It returns NULL if memory is not sufficient.
The syntax of malloc() function is given below:
1. ptr=(cast-type*)malloc(byte-size)
Let’s see the example of malloc() function
1. #include
2. #include
3. int main(){
4. int n.i,*ptr,sum=0;
5. printf(“Enter number of elements: “);
6. scanf(“%d”,&n),
7. ptr=(int* )malloc(n*sizeof(int)), //memory allocated using malloc
8. if(ptr==NULL)
ot
10. printf(“Sorry! unable to allocate memory”);
11. exit(0);
12.3
13. printf(“Enter elements of array: “);
14. for(i=0,i
2. #include
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf(“Enter number of elements: “);
6. canf(“%od" ,&n);
7. ptr=(int* )calloc(n,sizeof{ int), //memory allocated using calloc
8. if(ptr==NULL)
94
10. printf(“Sorry! unable to allocate memory”);
IL. exit(0);
12}
13. printf(“Enter elements of array: “),
14. for(i=0;i
#include
int main()
t
int *ptr, i, nl, n2;
printf(“Enter size of array: “);
scanf(“%d”, &n1);
ptr =(int*) malloc(n1 * sizeof{int));
printf(“Address of previously allocated memory:
‘)
for(i =0; i : It searches for a file named file in a list of directories specified
by you, then in a standard list of system directories.
#include "file": It searches for a file named file first in the current directory,
then in the same directories used for system header files.
Inclusion of header files:
User can create their own header file. Following program explain how to create
Example: Creating an user header | Example: use of an user header file
file
File name: factprogram.c
File name: fact.h #include
#include #include “fact.h”
int fact(int n) int main()
t t
int i=1,f=1;
while(i<=n)
{ printf(“factorial is %d\n”,i);
ffi; }
itt;
) Output: factorial is 120
Return f;Macro expansion: (#define)
Simple Macros
Syntax:
#define Template_name value
Note: Template_name replace with its value in program.
Example: #define upper 20
when we add above syntax in the program, wherever upper come it
replace with 20
#include
# define upper 20
int main()
int in=5;
i-uppertn;
printi(‘value of i is %d\n”,i);
5
Output: value of i is 25.
Macros with Arguments:
Here user pass an argument with the macro template .
Syntax:
#define Template_name(Arguments,...) (Expression)
Example:
#include
# define rectanglearea(a,b) (a*b)
int main()int a,b,area;
printf(‘enter a & b value\n”);
scanf(“%d%d" Ga, &b);
area=rectanglearea(a,b);
printf(‘area of rectangle is %d\n”,area);
Output:
Enter a & b value
2 5
area of rectangle is 10
Miscellaneous Directives: (#undef)
the #undef directive tells the preprocessor to remove the definitions for the
specified macro. A macro can be redefined after it has been removed by the
#undef directive.
Syntax:
#undef Template_name(Arguments,...) (Expression)
Example:
# define rectanglearea(a,b) (a*b) //macro definition
# undef rectanglearea(a,b) (a*b) _//macro undefined
# define rectanglearea(a,b) (a*b) //macro redefinedExample 1:
#include
# define area(a,b) (a*b)
# undef area(a,b) (a*b)
int main()
{
int a=2,b=11;
printf"area of
area(a,b));
return 0;
t
rectangle is. %d",
Output:
Error // area is not defined macro
Example 2:
#include
# define area(a,b) (a*b)
# undef area(a,b) (a*b)
# define area(a,b) (a*b)
int main()
int a=2,b=11;
printf'area of rectangle is %
Output:
area of rectangle is 22
Conditional compilation : (#ifdef, #ifndef, #endif)
Using conditional compilation, if user want, compiler to skip over part of code
by using preprocessing commands #ifdef and #endif
Syntax:
#ifdef macroname
Statement 1;
Statement 1;
#endif
If macronme has been #defind, the block of code will be processed as usual;
otherwise not.Example 1:
#include
# define rectanglearea(a,b) (a*b)
# define upper 2
int main()
{
int a,b,area;
#ifdef upper
printf("enter a & b value");
scanf{"%d%d" ,&a, 8b);
area=rectanglearea(a,b);
printf{"area of rectangle is %d",area);
tendif
Print{(“\n end of the program”):
return 0;
y
Output:
enter a & b value
57
area of rectangle is 35
end of the program
Example 2:
#include
# define rectanglearea(a,b) (a*b)
# define upper 2
int main()
t
int a,b,area;
#ifdef u
printf("enter a & b value");
scanf("%d%d" ,8a, 8b);
area=rectanglearea(a,b);
printf("area of rectangle is
%d" area);
endif
Printf(“\n end of the program’
return 0;
i
Output:
end of the program
* Sometimes we can use #ifndef, instead #ifdef.
* #iindef works exactly opposite to #ifdef.
Example:
#include
# define rectanglearea(a,b) (a*b)
# define upper 2
int main()
{
int a,b,area;
#ifndef upper
printf{"enter a & b value");
scanf{"%d%d" ,8:a, 8b);
area=rectanglearea(a,b);
printf{‘area of rectangle is %d",area);
endif
Printf(*\n end of the program”):
return 0;
,Output:
end of the program
#if, #else, #elif, #endif Directives:
The #if directive is used to test whether an expression evaluate to a nonzero
value or not. If result is non zerofie true) the subsequent line of code execute
upto #else, #elif or #endif comes; otherwise they are skipped.
Example: check number is +ve, -ve or zero.
#include
int main()
int num;
printf{"enter number");
scanf{"%d",&num);
#if num>0
printf("number is +ve\n");
#elif num<0
printf("number is -ve\n");
#else
printf("number is zero\n");
fendif
return 0;
Output: enter number
25
number is +ve
File:In C programming, file is a place on computer disk where information is stored
permanently. Which represents a sequence of bytes ending with an end-of-
file marker(EOF) .
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.
+ Ifyou 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 few commands in C.
+ You can easily move your data from one computer to another without
any changes.
‘Types of Files
1, Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or
any simple text editors.
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 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
I's).
They can hold higher amount of data, are not readable easily and provides a
better security than text files.
File Operations
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file4. Reading from and writing information to a file
Declaration for file Pointer:
When working with files, you need to declare a pointer of type file. This
declaration is needed for communication between the file and program.
Syntax:
FILE *file_pointer_name;
Example: FILE *fp;
Common File Functions
unction description
fopen() create a new file or open a existing file
felose() closes a file
getc() reads a character from a file
pute() writes a character to a file
fscanfl) reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point
Opening a File or Creating a File:
The fopen() function is used to create a new file or to open an existing file. this
function available in stdio.h file
Syntax:fp= fopen(“filename”, “mode”);
filename is the name of the file to be opened and mode specifies the purpose
of opening the file. Mode can be of following types,
Example:
{p= fopen(“sample.txt”, “w’
{p= fopen(“sample.txt’, “r’);
description
mode
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
rt opens a text file in both reading and writing mode
wt opens a text file in both reading and writing mode
at opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
If fopen( ) cannot open "test.dat " it will a return a NULL pointer which should
always be tested for as follows.
Example:
FILE *fp ;if ( ( fp = fopen( "test.dat", "r" ) ) == NULL )
{
puts( "Cannot open file’) ;
exit( 1) ;
}
This will cause the program to be exited immediately if the file cannot be
opened.
Closing a File:
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using library function fclose().
Syntax:
felose(file_pointer_name);
Example:
felose(fp); _//fp is the file pointer associated with file to be closed
Reading and writing to a text file:
For reading and writing to a text file, we use the functions fprintff) and fscanf{)
They are just the file versions of printil) and scanfl). The only difference is that,
fprint and fscanf expects a pointer to the structure FILE.
Writing to a text file:
Example 1: Write to a text file using fprintf{)
#include
int main()
{
int num;
FILE *fptr;
fptr = fopen("program.txt","w");
if(fptr == NULL)
{
printf("Error!”);
exit(1);,
printf("Enter num: ");
scanf{"%d" &anum);
fprintf{fptr,"%od" num);
felose(fptr);
return 0;
This program takes a number from user and stores in the file program. txt.
Reading from a text file
Example 2: Read from a text file using fscanf{)
#include
int main()
{
int num;
FILE *fptr;
if ((iptr = fopen("C:\ \program.txt","r")) == NULL)
printf{"Error! opening file");
// Program exits if the file pointer returns NULL,
exit(1);
}
fscanf{fptr,"%d", &num);
printf{"Value of n=%d", num);
felose(fptr);
return 0;
This program reads the integer present in the program.txt file and prints it
onto the screen.
If you succesfully created the file from Example 1, running this program will
get you the integer you entered.Command Line
Arguments
The arguments passed from command line are
called command line arguments. These
arguments are handled by main() function.
Command line argument is a parameter
supplied to a program when the program is
invoked. This parameter can be of any type.
In fact main can take two arguments called arge
and argv and the information contained in the
command line is passed on to the program
through these arguments, when main is called
up by the system.
The variable argc is an argument counter that
counts the number of arguments on the
command line. The argv is an argument vector
and represents an array of character pointers
that point to the command line arguments. In
order to access the command line arguments,
we must declare the main function