0% found this document useful (0 votes)
10 views

Unit-V

The document provides an overview of pointers in C, including their declaration, operations, and dynamic memory allocation using functions like malloc, calloc, and realloc. It also covers file handling concepts, including file pointers, opening and closing files, and different modes for file operations. Examples are provided to illustrate pointer usage and dynamic memory management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit-V

The document provides an overview of pointers in C, including their declaration, operations, and dynamic memory allocation using functions like malloc, calloc, and realloc. It also covers file handling concepts, including file pointers, opening and closing files, and different modes for file operations. Examples are provided to illustrate pointer usage and dynamic memory management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Ver 2.

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.

Pointers: A pointer is a variable that holds the address of a variable or a function.


Syntax:
Type_specifier *identifier

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 */

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 1


Ver 2.0

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

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 2


Ver 2.0

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;

printf("The value of ptr is : %p\n", ptr );


}
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

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 3


Ver 2.0

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

Ex: float *xp; (assume its address = 63498)


xp = xp + 5;
Will more the ptr to the address 63518

63498 + 5 * size of (float0

63498 + 5*4

63498+20

63518

Rules for pointer operation:

The following rules apply when performing operations on pointer variables

1. A pointer variable can be assigned to address of another variable.


2. A pointer variable can be assigned the values of another pointer variables.
3. A pointer variable can be initialized with NULL or 0 value.
4. A pointer variable can be prefixed or postfixed with increment and decrement operator.
5. An integer value may be added or subtracted from a pointer variable.
6. When 2 pointers points to the same array, one pointer variable can be subtracted from another.
7. When two pointers points to the objects of save data types, they can be compared using relational.
8. A pointer variable cannot be multiple by a constant.
9. Two pointer variables cannot be added

Dynamic Memory Allocation


•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.
PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 4
Ver 2.0

• 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.

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;

printf("Enter number of elements: ");


scanf("%d", &n);

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


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 5


Ver 2.0

printf("Enter elements: ");


for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
}

Example 2: calloc() and free()


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

ptr = (int*) calloc(n, sizeof(int));


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
}

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

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

printf("Addresses of previously allocated memory: ");


for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i);

printf("\nEnter new size of array: ");


scanf("%d", &n2);
ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory: ");


for(i = 0; i < n2; ++i)
printf("%u\n", ptr + i);
return 0;
}

When you run the program, the output will be:


Enter size of array: 2
Addresses of previously allocated memory:26855472
26855476

Enter new size of array: 4


Addresses of newly allocated memory:26855472
26855476
26855480
26855484

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.

These are of two types-

• 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

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. Mode Meaning


1. r Open a text file for reading
2. w Create a text file for writing
3 a Append to a text file
4. r+ Open a text file for read / Write
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>

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 8


Ver 2.0

void main()

FILE *fp;

fp=fopen(“lab.txt”,”w”);

if(fp==NULL)

printf(“The file could not open\n”);

fclose(fp);

Input/ Output Operations on Files


The fgetc() Function:

• fgetc() returns a character from the specified FILE.


• It also reads a character from file and increases the file pointer position.
• If any error or end of the file is reached it returned EOF.

Syntax
int fgetc(FILE *fp);

The fputc() Function:


• fputc() function is used to write characters to a file.
• fputc() function writes the character to the file shown by the file pointer.
• It also increases the file pointer position.

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>
void main()
{
FILE *fp;
char c;
fp=fopen("lines. txt", “w");
while( ( c=getchar())! =’\n’)
{
fputc( c,fp);
}
fclose(fp); fp=fopen("lines.
PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 9
Ver 2.0

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.

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 10


Ver 2.0

This process is called preprocessing.

• Commands used in preprocessor are called preprocessor directives and they begin with “#”

symbol. Below is the list of preprocessor directives that C language offers

S.no Preprocessor Syntax Description

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

#undef is used to undefine a defined macro variable. #Pragma is


4 Other directives #undef, #pragma
used to call a function before and after main function in a C program

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.
There are two types of macros

• Simple-macros do not take parameters.


• Parameterized-macros do take parameters (although the list of parameters may be
empty). The syntax for declaring a macro:

#define identifier token; // simple macro


PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 11
Ver 2.0

#define identifier (parameter1, parameter2,….) token; // parameterized macro


Example: Simple Macro
#include<stdio.h>
#include<conio.h>
#define pi 3.14 // simple
macro void main()
{
int r;
float A;
printf(“Enter radius”);
scanf(“%d”,&r);
A=pi*r*r;
printf(“Area of Circle is %f”,A);
getch();
}

Example: Parameterized Macro


#include<conio.h>
#define multiply(x, y) x*y // Parameterized macro
void main()
{
int z;
z=multiply(4, 5);
printf(“Value of z is %d”,z);
getch();
}
Output:
Value of z is 20

Example program for #define, #include preprocessors in C:


• #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'

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 12


Ver 2.0

#define letter_sequence "ABC"


#define backslash_char '\?'

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:

value of height : 100


value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
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:

#if, #ifdef, #ifndef, #else, #elif, #endif

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()

#define COMPUTER "An amazing device"

#ifdef COMPUTER

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 13


Ver 2.0

printf(COMPUTER);

#endif

Example: 2
#include <stdio.h>

#define x

10 void

main()

#ifdef x

printf("hello\n"); //this is compiled as x is defined

#else

printf("bye\n"); //this is not compiled

#endif

Passing Values to the Compiler


• The pragma directive is used to pass values and specify diverse options to the compiler.
• The options are specific for the compiler and the platform used.
• The pragma option configures some of the compiler options that can otherwise be configured from the
command line.

#pragma token-sequence

The following are the commonly used forms of the pragma directive:

1. #pragma option

S.No. Option Role


1. -C Allows nested comments
2. -C- Does not allow comments
3. -r Enables the use of register variables

Example:

#include<stdio.h>

#pragma option -C

void main()

/*Start of outer comment

/*inner comment*/

End of outer comment*/

printf(“By default nested comments are not allowed \n”);


PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 14
Ver 2.0

printf(“pragma option –C makes them allowed”);

Turbo C++ supports the following #pragma directives:

➢ #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>

int main( int argc, char *argv[] ) {

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.

PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura Page | 15

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy