PPS-Unit-5 Notes
PPS-Unit-5 Notes
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 a=10;
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 swap(int *,int *);
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
1. Referencing a Pointer
2. Dereferencing a Pointer
3. Assigning to a Pointer
4. 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 val=12.5; 12.5
8200
float *fptr;
6000 8200
fptr=&val;
Dereferencing a Pointer
1. An object pointed to or referenced by a pointer can be indirectly accessed by dereferencing the
pointer.
2. A dereferencing operation allows a pointer to be followed to the data object to which it points.
3. A pointer can be dereferenced by using a dereference operator (*).
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int val=12;
int *iptr=&val;
printf(“\nAddress of val is %p”,iptr);
printf(“\nValue of val is %d”,*iptr);
getch();
}
Output:
Values of val is 12
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;
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>
#include<conio.h>
void main ()
{
int *ptr = NULL;
Output:
The value of ptr is 00000000
Pointer Arithmetic:
An integer operand can be used with a pointer to move it to a point / refer to some other address in the memory.
Consider an int type ptr as follows
int * mptr;
65494
mptr
Assume that it is allotted the memory address 65494 increment value by 1 as follows.
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
xp = xp + 5;
An array is a collection of fixed number of values of a single type. That is, you need to declare the
size of an array before you can use it.
Sometimes, the size of array you declared may be insufficient. To solve this issue, you can allocate
memory manually during run-time. This is known as dynamic memory allocation in C programming.
There are 4 library functions defined under <stdlib.h> makes dynamic memory allocation in C
programming. They are malloc(), calloc(), realloc() and free().
1. 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.
2. 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.
3. 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.
Example 1: malloc() and free()
This program calculates the sum of n numbers entered by the user. To perform this task, memory is
dynamically allocated using malloc(), and memory is freed using free() function.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n, i, *ptr, sum = 0;
This program calculates the sum of n numbers entered by the user. To perform this task, calloc() and free()
is used.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
4. 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()
Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
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
FILE *pointer_name;
Example
FILE *fp1,*fp2; // fp1,fp2 are file pointers
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);
Sr.No Mod Meanin
. e g
1. R Open a text file for reading
2. W Create a text file for writing
3 A Append to a text file
r+ Open a text file for read / Write
4.
5. W+ Create a text file for read/ write
6. A+ Append or create a text file for read/ write
Example: 1
FILE
*fp1;
FILE
*fp2;
fp1=fopen(“Listing.txt”,”w”);
Example: 2
FILE *fp;
fp=fopen(“Listing.txt”,”r”);
if(fp==NULL)
{
printf(“The file could not open\n”);
}
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>
#include<conio.h>
void main()
{
FILE *fp;
fp=fopen(“lab.txt”,”w”);
if(fp==NULL)
{
printf(“The file could not open\n”);
}
fclose(fp);
getch();
}
Input/ Output Operations on Files
The fgetc() Function:
Syntax:
int fputc(int ch, FILE *p);
Here, p is the file pointer.
Example: 4 Write a program in C to write text to a file using fputc() and read the text from the same file
using fgetc()
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("lines. txt", “w");
while( ( c=getchar())!=’\n’)
{
fputc( c,fp);
}
fclose(fp);
fp=fopen("lines.txt","r");
while(( c=fgetc(fp))!=EOF)
{
printf("%c",c );
}
fclose(fp);
getch();
}
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.
This process is called preprocessing.
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.
Header Files Inclusion
The #include directive tells the preprocessor to grab the text of a file and place it directly into the current file.
Typically, such statements are placed at the top of a program--hence the name "header file" for files thus included.
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.
Output:
Value of z is 20
#define - This macro defines constant value and can be any of the basic data types.
#include <file_name> - The source code of the file “file_name” is included in the main C program where
“#include <file_name>” is mentioned.
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
}
Output:
value of backslash_char : ?
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*/
2. #pragma argsused
3. #pragma exit
4. #pragma hdrfile
5. #pragma hdrstop
6. #pragma inline
7. #pragma option
8. #pragma saveregs
9. #pragma startup
10. #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 ) {