0% found this document useful (0 votes)
9 views16 pages

Unit 5 PPS

ll

Uploaded by

irshadumam6
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)
9 views16 pages

Unit 5 PPS

ll

Uploaded by

irshadumam6
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/ 16

Pointer: Pointer is a variable which is used to store the memory address of another

variable

Pointer declaration:

syntax:
Data type *variable name;
Example:

int *x; // x is pointer to integer (means x is a pointer which will store address of a
integer variable)

float *y; // y is pointer to float(means x is a pointer which will store address of a


float variable)

char *z ; // z is pointer to character(means x is a pointer which will store address


of a char variable)

Pointer notation:

int i=3;

This declaration tells the C compiler to:

(a) Reserve space in memory to hold the integer value.

(b) Associate the name i with this memory location.

(c) Store the value 3 at this location.

We may represent i’s location in memory by the following memory map.

We see that the computer has selected memory location 65524 as the place to store the
value 3.

EXAMPLE 1:

#include<stdio.h>

void main ( )

int i = 3 ;

printf ( "\nAddress of i = %u", &i ) ;

printf ( "\nValue of i = %d", i ) ;

printf ( "\nValue of i = %d", *( &i ) ) ;


}

The output of the above program would be:

Address of i = 65524

Value of i = 3

Value of i = 3

EXAMPLE 2: consider i j

#include<stdio.h> 3 65524
void main( ) 65524 65522

{int i = 3 ;

int *j ;

j = &i ;

printf ( "\nAddress of i = %u", &i ) ;

printf ( "\nAddress of i = %u", j ) ;

printf ( "\nAddress of j = %u", &j ) ;

printf ( "\nValue of j = %u", j ) ;

printf ( "\nValue of i = %d", i ) ;

printf ( "\nValue of i = %d", *( &i ) ) ;

printf ( "\nValue of i = %d", *j ) ;

The output of the above program would be:

Address of i = 65524

Address of i = 65524

Address of j = 65522

Value of j = 65524

Value of i = 3

Value of i = 3

Value of i = 3
USE OF POINTER IN 'C'

OPERATOR NAME USE AND MEANING OF OPERATOR

* Asterisk Declares a pointer in a program

Returns the referenced variable's value

& Ampersand Return a variable's address

EXAMPLE 3:

WAP TO ADD TWO NUMBERS USING POINTER

#include<stdio.h>

#include<conio.h>

void main()

int num1, num2, sum;

int *ptr1, *ptr2;

printf("Enter any two Number: ");

scanf("%d%d", &num1, &num2);

ptr1 = &num1;

ptr2 = &num2;

sum = *ptr1 + *ptr2;

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

getch();

Applications of Pointer:

1) Enable the programmers to return multiple values from a function

2) Use for dynamic memory allocation


3) To create complex data structure such as trees, linked list, stack, queue and graphs

POINTER TO POINTER:

When a pointer variable store the address of another pointer variable then it is called
pointer to pointer.

Example: int i=3;

int *j, **k;

j=&i;

k=&j

POINTER ARITHMETIC:

1: ADDRESS+NUMBER GIVES ADDRESS

2: ADDRESS –NUMBER GIVES ADDRESS

3: ADDRESS-ADDRESS GIVES NUMBER

4: ADDRESS+ADDRESS ILLEGAL (CAN’T PERFORM)

5: WE CAN NOT MULTIPLY ADDRESS WITH A NUMBER

6: WE CAN NOT DIVIDE ADDRESS WITH A NUMBER

Dynamic memory allocation in C


The concept of dynamic memory allocation in c 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.

1. malloc( )

2. calloc( )

3. realloc( )

4. free( )
static memory allocation dynamic memory allocation

Memory is allocated at compile time. Memory is allocated at run time.

Memory is allocated automatically when a Memory is allocate using


definition statement is written, eg: int malloc( ) or calloc ( ) function
x[100] ,automatically 200 byte memory
will allocate

Memory can't be changed while executing memory can be changed while


program. executing program.

Used in array. used in linked list.

malloc( )

1. The malloc () function allocates single block of requested memory.


2. It doesn't initialize memory at execution time, so it has garbage value initially.
3. Takes one argument
4. It returns NULL if memory is not sufficient.

Syntax:
Pointer_variable= (cast-type*) malloc(byte-size)
For Example: int *x;
x = (int*) malloc(100 * sizeof(int));

Since the size of int is 2 bytes, this statement will allocate 200 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory.

calloc( )

1. “calloc” or “contiguous allocation” function allocates multiple block of requested


memory.
2. It initializes each block with a default value ‘0’.
3. It takes two parameters or arguments as compare to malloc( ).
4. It also returns NULL if memory is not sufficient.

Syntax:
Pointer_variable = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
For Example: float *x;
x= (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size
of the float.

realloc( ):
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc( ) or calloc( ) is insufficient, realloc( ) can be used
to dynamically re-allocate memory.
Syntax:
Pointer_variable = realloc(pointer_variable, newSize);

free( )

“free” method in C is used to dynamically de-allocate the memory. The memory allocated
using functions malloc() and calloc() is not de-allocated on their own. Hence the free()
method is used
Syntax:
free(pointer_variable);
EXAMPLE: WAP TO FIND THE SUM OF N NUMBERS USING DYNAMIC MEMORY
ALLOCATION
#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 ("unable to allocate memory");
exit (0);
}
printf("Enter elements of array: ");
for(i=0;i<=n-1;++i)
{ scanf("%d",ptr+i);
sum=sum+*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
}

C PREPROCESSOR:

The program that sorts out all the directives before compilation is called preprocessor

SOURCE CODE WITH


SOURCE CODE PREPROCESSOR PROPERLY SORTED
DIRRECTIVE BEFORE
COMPILATION

ROLE OF PREPROCESSOR

The statement that begin with # symbol are called preprocessor directives. These are
divided into three categories in C

1) MACRO SUBSTITUTION (# define)


2) CONDITIONAL COMPILATION (#if,#else,#elif,#endif etc)
3) FILE INCLUSION DIRECTIVE (#include)

1)MACRO SUBSTITUTION OR REPLACEMENT DIRECTIVES:

macro is an identifier name which replaces its value whereever it appears in a program. it
begins with # define
TYPES OF MACRO:
1. SIMPLE MACRO: it is also known as symbolic constant
syntax: # define macro_ name replacement_list
ex: WAP TO FIND THE AREA OF CIRCLE USING MACRO
#include<stdio.h>
#include<conio.h>
#define PI 3.1416//macro
void main()
{
float area, radius;
clrscr();
printf("Enter the radius of circle ");
scanf("%f",&radius);
area=PI*radius*radius;
printf("\nThe Area of the Circle is = %f",area);
getch();
}
2.FUNCTION LIKE MACRO:
A macro with argument is known as function like macro.
syntax: # define macro_name(argument) replacement_list
EX: WAP TO FIND THE SQUARE OF A NO.
#include <stdio.h>
#include <conio.h>
#define SQR(x) (x * x)
void main()
{
int x,s;
printf("Enter any number to find square");
scanf("%d", &x);
s= SQR(x);
printf("SQUARE = %d",s);
getch();
}
3.NESTED MACRO:
when a macro can be used in another macro then it is called nested macro.
#include <stdio.h>
#include <conio.h>
#define SQR(x) (x * x)
#define CUBE(x) (SQR(x)*x)
void main()
{
int x,s;
printf("Enter any number to find cube");
scanf("%d", &x);
s= CUBE(x);
printf("CUBE = %d",s);
getch();
}

2)CONDITIONAL COMPILATION:

Conditional Compilation directives help to compile a specific portion of the program or


skip compilation of some specific part of the program based on some conditions.

Examples are: #if,#elif,#endif,#else,#ifdef,#ifndef

Some directives and their use:

PREPROCESSOR DIRECTIVES USE,MEANING OR PURPOSE


DIRECTIVES

Used to make the compilation of code


# if conditional

CONDITIONAL
DIRECTIVES Used to give default statements with
# else #if,#ifdef and #ifndef

Used to give multiple conditions


#elif
Used to make conditional compilation
#ifdef when a macro is already defined

Used to make conditional compilation


#ifndef when a macro is not already defined

Used to end the conditional compilation


#endif block

#define Used to define a macro


UNCONDITIONAL
#undef Used to undefined a macro
DIRECTIVES
#include Used to include a header file in the
program
#error Stop compilation when an error occurs
EXAMPLE:

#include<stdio.h>

#define marks 60

void main()

#if marks>80

printf(“distinction”);

#elif marks>=60

printf(“first division”);

#else

printf(“unsuccessful”);

#endif

3)FILE INCLUSION DIRECTIVES:

The directive that are used to link header file in a program are called file inclusion
directives. The directive #include is used to include header file in a program.

The header file may include in two ways:

1.#include<filename.h> // this statement searches in standard c library


locations

2. #include “filename.h” // this statement first searches in current directory


then in Standard c library locations.
LINKED LIST: Like arrays, a Linked List is a linear data structure. Unlike arrays, linked
list elements are not stored at a contiguous location; the elements are linked using
pointers. They include a series of connected nodes. Here, each node stores the data and
the address of the next node.

Linked-List

Advantages of Linked-List
Here are a few advantages of a linked list that is listed below.
 Dynamic Data structure: The size of memory can be allocated or de-allocated at run
time based on the operation insertion or deletion.
 Ease of Insertion/Deletion: The insertion and deletion of elements are simpler than
arrays since no elements need to be shifted after insertion and deletion, just the address
needed to be updated.
 Efficient Memory Utilization: As we know Linked List is a dynamic data structure the
size increases or decreases as per the requirement so this avoids the wastage of
memory.
 Implementation: Various advanced data structures can be implemented using a linked
list like a stack, queue, graph, hash maps, etc.

Types of Linked Lists:


 Singly Linked List – In this type of linked list, one can move or traverse the linked list
in only one direction. where the next pointer of each node points to other nodes but the
next pointer of the last node points to NULL.

A linked list node


/* Node of a singly linked list */
struct Node
{
int data;
struct Node* next;
};

 Doubly Linked List – In this type of linked list, one can move or traverse the linked list
in both directions (Forward and Backward)

/* Node of a doubly linked list */


struct node
{
int data;
Node* next; // Pointer to next node in DLL
Node* prev; // Pointer to previous node in DLL
};

 Circular Linked List – In this type of linked list, the last node of the linked list contains
the link of the first/head node of the linked list in its next pointer.

/* Node of a circular linked list */

struct node
{
int data;
struct node* next;
};

 Doubly Circular Linked List – A Doubly Circular linked list or a circular two-way linked
list is a more complex type of linked list that contains a pointer to the next as well as
the previous node in the sequence. The difference between the doubly linked and circular
doubly list is the same as that between a singly linked list and a circular linked list. The
circular doubly linked list does not contain null in the previous field of the first node.
/* Node of a doubly circular linked list */

struct node

int data;

struct node* next;

struct node* prev;

};

COMMAND LINE ARGUMENT:

The arguments passed from command line are called command line arguments. These
arguments are handled by main () function.

To support command line argument, we need to change the structure of main () function as
given below.

main (int argc, char *argv[])

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name
always.

EXAMPLE OF COMMAND LINE ARGUMENT:

#include<stdio.h>

#include<conio.h>

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

int i;

printf("Total number of arguments: %d",argc);

for(i=0;i< argc;i++)

printf("\n %d argument: %s",i,argv[i]);

getch ();

}
OUTPUT:

C:/TC/BIN>TCC cmdprogram.c
C:/TC/BIN>cmdprogram 10 20
Number of Arguments: 3
0 arguments c:/tc/bin/cmdprogram.exe
1 arguments: 10
2 arguments: 20

WHAT IS A FILE?
A named collection of data stored in secondary storage (typically). The output of a C program
is generally deleted when the program is closed. Sometimes, we need to store that output
for purposes like data analysis, result presentation, comparison of output for different
conditions, etc. The use of file handling is exactly what the situation calls for.
Files are stored as a sequence of bytes logically contiguous. The last byte of a file
contains the end of file character (EOF), while reading a text file, the EOF character can be
checked to know the end.
There are two types of files in c
1. TEXT FILE: contain ASCII codes only. Text files are the normal .txt files that we can easily
create using Notepad or any simple text editors. When we open those files, we'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 FILE: can contain non-ASCII characters, image, audio, video, executable etc.
Binary files are mostly the .bin files in our computer. Instead of storing data in plain text,
they store it in the binary form (0's and 1's).They can hold higher amount of data, are not
readable easily and provides a better security than text files.
To check the end of file here the file size value needs to be checked
FILE HANDLING IN C
In C we use FILE * to represent a pointer to a file. Following is the general format for declaring
and opening file.
FILE *fptr note: *fptr is file pointer
fptr=fopen(“file name”,mode);

FUNCTION NAME SYNTAX PURPOSE

fopen() fptr=fopen(“file name”,mode); create a new file for use


where fptr is file type pointer and
open an existing file
fclose() fclose(fptr) to close a file
where fptr is file type pointer

fgetc() ch=fgetc(fptr) to read a character from a


where fptr is file type pointer file
and ch is character variable

fputc() fputc(ch,fptr)
where fptr is file type pointer to write a character into a
and ch is character variable file

fscanf() fscanf(fptr,”control to read a formatted data


string”,&list) from a specified file
where fptr is file pointer to
receive formatted data

fprintf() fprintf(fptr,”control string”, to write formatted data into


list) a specified file
where fptr is file pointer to
write formatted data

File Opening Mode:


fopen Returns if FILE-
Mode Meaning
Exists Not Exists

r Reading – NULL

w Writing Over write on Existing Create New File

a Append – Create New File

New data is written at the beginning


r+ Reading+ Writing Create New File
overwriting existing data

w+ Reading+ Writing Over write on Existing Create New File

New data is appended at the end of


a+ Reading+Appending Create New File
file
Programs:
1. Wap To Copy The Content Of One File Into Another File
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("abc.txt", "r");
fp2 = fopen("xyz.txt", "w");
if(fp1==NULL||fp2==NULL)
{
printf(“File could not open!!”);
exit(0);
}
while((ch = fgetc(fp1)) != EOF)
fputc(ch, fp2);
fclose(fp1);
fclose(fp2);
getch();
}
2. Wap To Count The Number Of Characters Present In A File
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
FILE *fp;
char name[50];
int count=0;
printf(“enter name of file”);
gets(name);
fp=fopen(name,”r”);
if(fp= =NULL)
{
printf(“File could not open!!”);
exit(0);
}
while(fgetc(fp)!=EOF)
Count++;
Printf(“no of characters in file=%d”,count);
}

(Q).What do you mean by enumerated data type?


Ans. The data type that attach names to numbers are called enumerated data type. it is
a user defined data type, the names make a program easy to read and maintain. The
keyword enum is used.
It start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list.

Syntax: enum identifier {value1, value2,.... Value n};


EXAMPLE:
#include< stdio.h>
void main()
{
int i;
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC};
clrscr();
for(i=JAN;i<=DEC;i++)
printf("\n%d",i);
}
OUTPUT: 01234567891011
LINKER AND LOADER

Linker: A linker is a program that combines object modules to form an executable


program. Programming languages allow you to write different pieces of code, called modules,
separately. This simplifies the programming task because you can break a large program into
small, more manageable pieces. Though, we need to put all the modules together. This is the
job of the linker.
In addition to combining modules, a linker also replaces
symbolic addresses with real addresses. Therefore we need to link a program even if it
contains only one module.

Loader: Loader is a program that loads the executable file into the system memory for
execution. Loader loads executable file with absolute format by simply copying it into system
memory.

You might also like