Unit-V
Unit-V
Unit-V
Pointers: Introduction, declaration, applications, Introduction to dynamic memory allocation (malloc, calloc, realloc,
free), Use of pointers in self-referential structures, notion of linked list (no implementation)
File handling: File I/O functions, Standard C preprocessors, defining and calling macros, command-line arguments.
Example: 1
int *iptr; //iptr is pointer to an integer
float *fptr; //fptr is pointer to a float
char *cptr; //cptr is pointer to a character
Example: 2
int *iptr=&a;
iptr 20001 a 10
Example: 3
float fval=12.5;
float *fptr;
fptr=&fval;
fptr fval
8200 12.5
6000 8200
Address
• A variable is declared by giving it a type and a name (e.g. int k;)
• Pointer variable declarations are read from the right side. The punctuator * is read as ‘pointer to’.
• Every pointer variable takes the same amount of memory space irrespective of whether it is a pointer to int,
float, char or any other type.
• A pointer can be assigned or initialized with address of an object.
• A pointer variable cannot hold a non-address value and thus can be assigned or initialized with l-values. An
"lvalue" of a variable is the value of its address, i.e. where it is stored in memory.
• A pointer variable is declared by giving it a type and a name (e.g. int *ptr) where the asterisk tells the compiler
that the variable named ptr is a pointer variable and the type tells the compiler what type the pointer is to point
to (integer in this case).
• Once a variable is declared, we can get its address by preceding its name with the unary & operator, as in &k.
• We can "dereference" a pointer, i.e. refer to the value of that which it points to, by using the unary '*' operator
as in *ptr.
• To check for a null pointer, you can use an if statement as follows:
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Example: To write a program in C to swap the value of two variables a and b using pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=1,b=99;
printf(“\n Before Swapping”);
printf(“ a=%d, b=%d\n”,a,b);
swap(&a,&b);
printf(“\n After Swapping”);
printf(“ a=%d, b=%d\n”,a,b);
getch();
}
void swap(int *p1,int *p2)
{
int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
}
Output:
a=1, b=99
a=99,b=1
Operations on Pointers
Referencing a Pointer
Dereferencing a Pointer
Assigning to a Pointer
Pointer Arithmetic
Referencing a Pointer
In this, a pointer variable is made to refer to an object.
The reference to an object can be created with the help of reference operator (&).
Example: fptr fval
float fval=12.5; 12.5
8200
float *fptr; 6000 8200
fptr=&val;
Dereferencing a Pointer
An object pointed to or referenced by a pointer can be indirectly accessed by dereferencing the pointer.
A dereferencing operation allows a pointer to be followed to the data object to which it points.
A pointer can be dereferenced by using a dereference operator (*).
Example:
#include<stdio.h>
void main() Output:
{ Address of val is 0024FEA8
int val=12;
Values of val is 12
int *iptr=&val;
printf(“\nAddress of val is %p”,iptr);
printf(“\nValue of val is %d”,*iptr);
}
Note: %p format specifier for printing address
Assigning to a Pointer
A pointer can be assigned or initialized with the address of an object.
A pointer variable cannot hold non-address value.
Example: Valid
Not Valid
int val=10; int val=10;
int *iptr=val; int *iptr=&val;
NULL Pointers
Zero or NULL can be assigned to a pointer.
It is always a good practice to assign a NULL value to a pointer variable in case you do not have exact address to
be assigned.
The NULL pointer is a constant with a value of zero.
Example:
#include <stdio.h> Output:
void main () The value of ptr is 00000000
{
int *ptr = NULL;
6549
4
Int * mptr ; mptr
Assume that it is allotted the memory address 65494 increment value by 1 as follows.
mptr ++; or ++ mptr;
mptr = mptr +1; or mptr + =1 ;
++ and - - operators are used to increment, decrement a ptr and commonly used to move the ptr to next location. Now
the pointer will refer to the next location in the memory with address 64596
C language automatically adds the size of int type (2 bytes) to move the ptr to next memory
location. mptr = mtpr + 1
= 645.94 + 1 * sizeof (int)
= 65494 + 1 * 2
Similarly, an integer can be added or subtract to move the pointer to any location in RAM. But the resultant address
is dependent on the size of data type of ptr.
The step in which the ptr is increased or reduced is called scale factor. Scale factor is nothing but the size of data
type used in a computer.
We know that in a pc,
The size of float = 4 char = 1 double = 8 and so on
• There are 4 library functions defined under <stdlib.h> makes dynamic memory allocation in C programming. They
are malloc(), calloc(), realloc() and free().
malloc()
• The name "malloc" stands for memory allocation.
• The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of
type void which can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Example:
ptr = (int*) malloc(100 * sizeof(int));
Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the
address of the first byte in the allocated memory.
However, if the space is insufficient, allocation fails and returns a NULL pointer.
C calloc()
• The name "calloc" stands for contiguous allocation.
• The malloc() function allocates a single block of memory. Whereas, calloc() allocates multiple blocks of memory
and initializes them to zero.
Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of float.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You
must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
void main()
{
int n, i, *ptr, sum = 0;
C realloc()
If the dynamically allocated memory is insufficient or more than required, you can change the size of
previously allocated memory using realloc() function
Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with new size x.
Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 6
Ver 2.0
File handling
Concept of a File:
• We use file for storing information which can be processed by our program. Such files are called data files.
• In order to store information permanently and retrieve it, we need to use data files.
• Text File: Text file consists of consecutive characters. Characters can be strings or numbers.
• Binary files (Unformatted data file): They organize data into blocks of continuous byte of information. These
blocks represent complex data structures such as arrays and structures.
File Handling
How to write information to a file and how to read information from a file.
Streams
• A stream is a sequence of elements in time.
• Only one element, the current, is available at a time.
• All of C file structures are byte streams.
File Pointer
• C communicates with file for reading and writing a new data types called a file pointer.
• Every file we open, has its own file pointer variable.
• When we wish to write to a file, we specify the file by using its file pointer variable.
Syntax
PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 7
Ver 2.0
FILE *pointer_name;
Example
Header File
For file handling, header file #include<stdio.h> is used.
Opening a File
• First step in using a file is to open it.
• File can be used in different ways, for reading from, or writing or both.
• We can tell the input/output system about the file we want to open by means of a mode string.
• This gives information about the types of file we are working on and way in which it to be used.
Syntax
File_pointer_name=fopen(file_name,mode);
FILE *fp1;
FILE *fp2;
fp1=fopen(“Listing.txt”,”w”);
Example: 2
FILE *fp;
fp=fopen(“Listing.txt”,”r”);
if(fp==NULL)
Closing a File
• A file must be closed as soon as all operations on it have been completed.
• All the information associated with the file is flushed out from the buffers.
Syntax
fclose(file_pointer);
Example: 3
#include<stdio.h>
void main()
FILE *fp;
fp=fopen(“lab.txt”,”w”);
if(fp==NULL)
fclose(fp);
Syntax
int fgetc(FILE *fp);
Syntax:
int fputc(int ch, FILE *p);
txt","r"); while((
c=fgetc(fp))!=EOF)
{
printf("%c",c ); fclose(fp);
}
}
Example: 5 write a program in C to copy content of one file (source) to other file (destination) using file handling.
#include<stdio.h>
#include<conio.h>
void main()
char c;
FILE *source,*target;
source=fopen("Source.txt","r");
target=fopen("target.txt","w");
if(source==NULL)
{
fclose(source);
printf("Sorce File doesn't exist");
}
else
{
while( (c=fgetc(source))!=EOF)
{
fputc(c,target);
}
printf("File copied
successfully\n"); fclose(source);
fclose(target);
}
getch();
}
Standard C
Preprocessors
C Preprocessor directives:
• Before a C program is compiled in a compiler, source code is processed by a program called preprocessor.
• Commands used in preprocessor are called preprocessor directives and they begin with “#”
This macro defines constant value and can be any of the basic data
1 Macro #define
types.
Header file The source code of the file “file_name” is included in the main
2 #include <file_name>
inclusion program at the specified place
Conditional #ifdef, #endif, #if, Set of commands are included or excluded in source program before
3
compilation #else, #ifndef compilation with respect to the condition
A program in C language involves into different processes. Below diagram will help you to understand all the processes
that a C program comes across.
Macro Definition
A macro is a name given to a block of C statements as a pre-processor directive. A macro is defined with the
preprocessor directive, #define.
There are two types of macros
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n",
letter_sequence); printf("value of backslash_char : %c
\n", backslash_char);
}
Output:
Conditional Compilation:
Conditional compilation as the name implies code is compiled if certain condition(s) hold true. Normally we use if
keyword for checking some condition so we have to use something different so that compiler can determine whether
to compile the code or not.
Conditional compilation means that a part of a program is compiled only if a certain condition comes out to be true.
The following are the available conditional compilation directives:
The following are the important points about the use of conditional compilation directives:
The conditional compilation preprocessor directive can appear anywhere in the program.
The statements set can be empty or can even have preprocessor directive(s) or C statement(s).
Example: 1
#include
<stdio.h> void
main()
#ifdef COMPUTER
printf(COMPUTER);
#endif
Example: 2
#include <stdio.h>
#define x
10 void
main()
#ifdef x
#else
#endif
#pragma token-sequence
The following are the commonly used forms of the pragma directive:
1. #pragma option
Example:
#include<stdio.h>
#pragma option -C
void main()
/*inner comment*/
➢ #pragma argsused
➢ #pragma exit
➢ #pragma hdrfile
➢ #pragma hdrstop
➢ #pragma inline
➢ #pragma option
➢ #pragma saveregs
➢ #pragma startup
➢ #pragma warn
Command-Line Arguments
• It is possible to pass some values from the command line to your C programs when they are executed.
• These values are called command line arguments and many times they are important for your program
especially when you want to control your program from outside instead of hard coding those values inside the
code.
• The command line arguments are handled using main() function arguments where argc refers to the number of
arguments passed, and argv[] is a pointer array which points to each argument passed to the program.
• Following is a simple example which checks if there is any argument supplied from the command line and take
action accordingly
Example:
#include <stdio.h>
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing
Output: The argument supplied is testing
When the above code is compiled and executed with two arguments, it produces the following result.
$./a.out testing1 testing2
Output: Too many arguments supplied.