pointers every computer has addressable memory locations. identifiers are assigned to data and their...

125
Pointers Pointers Every Computer has Every Computer has addressable memory addressable memory locations. Identifiers locations. Identifiers are assigned to data and are assigned to data and their contents are their contents are manipulated. manipulated.

Upload: sherilyn-daniels

Post on 16-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

PointersPointers

Every Computer has addressable Every Computer has addressable memory locations. Identifiers are memory locations. Identifiers are

assigned to data and their contents are assigned to data and their contents are manipulated. manipulated.

Example In a C program, we can Example In a C program, we can have have

void main()void main(){int a,b;{int a,b; /*variable is assigned a /*variable is assigned a a=3;a=3; value & manipulated,value & manipulated,printf(“%d”,a,&a); & is called printf(“%d”,a,&a); & is called

ampersand */ampersand */a=5;a=5;b=a;b=a; printf(“%u”,b,&b);printf(“%u”,b,&b);}}

• A Pointer is a derived datatypeA Pointer is a derived datatype

• It is a data type built from one of the It is a data type built from one of the standard types i.e. int, float, char, doublestandard types i.e. int, float, char, double

• Pointer’s value is any of the addresses Pointer’s value is any of the addresses available in the computer for storing and available in the computer for storing and accessing the dataaccessing the data

• Pointers are built on the concept of pointer Pointers are built on the concept of pointer constants or addresses constants or addresses

Fig - Character constants & Fig - Character constants & variablesvariables

We can have a Character We can have a Character constant i.e any letter of the constant i.e any letter of the alphabet that can be drawn alphabet that can be drawn from universe of all charactersfrom universe of all charactersA Character constant can be a value and A Character constant can be a value and storedstored

In a variable say ‘G’ stored in achar, a In a variable say ‘G’ stored in achar, a variablevariable

given by the programmer. In 1 MB of given by the programmer. In 1 MB of computer’scomputer’s

memory, imagine 145600 to be a memory memory, imagine 145600 to be a memory locationlocation

in which character constant ‘G’ is stored.in which character constant ‘G’ is stored.

A Program define 2 pointers and A Program define 2 pointers and print their addresses as pointersprint their addresses as pointers

#include <stdio.h> /*prg to print character #include <stdio.h> /*prg to print character */*/

int main()int main() /*addresses*//*addresses*/{ { char a,b;char a,b;printf(“%p %p\n”,&a,&b);printf(“%p %p\n”,&a,&b);return 0;return 0;}}

To access a variable through a To access a variable through a ptr p, code int *p,a; p=&aptr p, code int *p,a; p=&a

• *->indirection operator *->indirection operator

• Indirection is a unary operatorIndirection is a unary operator

• Indirection and address operators are Indirection and address operators are inverse of each otherinverse of each other

Initialization Of Pointer Initialization Of Pointer VariablesVariables

• C Language doesn’t initialize variables.C Language doesn’t initialize variables.

• If at all it initializes , it is done by the system If at all it initializes , it is done by the system loader.loader.

• Hence when we start our program, all of our Hence when we start our program, all of our uninitialized variables have unknown garbage in uninitialized variables have unknown garbage in them.them.

• An OS clears the memory when it loads a An OS clears the memory when it loads a program which cant be counted especially with program which cant be counted especially with programs that run on multiple systemsprograms that run on multiple systems

Figure-Uninitialized pointers-such Figure-Uninitialized pointers-such errors are difficult to debug because it errors are difficult to debug because it is delayed till program executionis delayed till program execution

?

?

a

p

int a;

int *p;

Some garbage: Unknown value

Different garbage:

Pointer to unknown value

• To correct the problem, always assign a valid To correct the problem, always assign a valid address to the pointer.address to the pointer.

• Int a;Int a;• Int *p=&a;Int *p=&a;• *p=89;*p=89;• Its also possible initialize pointers when they Its also possible initialize pointers when they

are declared and defined. Dv should be are declared and defined. Dv should be defined before the pointer variable.defined before the pointer variable.

Pointers and FunctionsPointers and Functions

• C uses Pass by value concept exclusively i.e. C uses Pass by value concept exclusively i.e. • Only direct way to send something back from a udf function Only direct way to send something back from a udf function

is through return value.is through return value.• Pass by address concept is simulated by passing address.Pass by address concept is simulated by passing address.• When we pass by address, we pass the pointer to the When we pass by address, we pass the pointer to the

variable.variable.• When we use pass by value method, the data is exchanged in When we use pass by value method, the data is exchanged in

the called function, but nothing changes in the calling the called function, but nothing changes in the calling function. We see unworkable & workable exchange function. We see unworkable & workable exchange programs xchg.c , xchg1.cprograms xchg.c , xchg1.c

Pass By valuePass By value

7

5 7

5

a b

temp

5

No Change

x y

Exchanged

Rather than pass values of 2 to be exchanged , Rather than pass values of 2 to be exchanged , we could pass pointer to the valueswe could pass pointer to the values

1 To exchange using pointers, create pointers using the 1 To exchange using pointers, create pointers using the address operator in the function call.address operator in the function call.

xchg( &a , &b);xchg( &a , &b);2.To use pass by address, the formal parameters in the called 2.To use pass by address, the formal parameters in the called

function are passed as pointer to variablesfunction are passed as pointer to variables void xchg(int *, int *); void xchg(int *, int *); 3.To assign a value to a, dereference the pointer in xchg.3.To assign a value to a, dereference the pointer in xchg. This allows us to access data in the calling program using This allows us to access data in the calling program using

call by address.call by address. When we need to return more than 1 value from a function, When we need to return more than 1 value from a function,

we can use pointerswe can use pointers

7

&a

8

&b

temp

5

After Exchange

Functions Returning PointersFunctions Returning Pointers

• We can have a function from returning a We can have a function from returning a pointer to a calling functionpointer to a calling function

• As an Example , u have a program to find As an Example , u have a program to find smaller of 2 variables. We pass 2 pointers to smaller of 2 variables. We pass 2 pointers to the function that uses a conditional expression the function that uses a conditional expression to determine which value is smallerto determine which value is smaller

• Return value is the address of smallest no. as a Return value is the address of smallest no. as a pointer. pointer.

Example for Function returning pointers.Example for Function returning pointers.Prototype declarationPrototype declaration

int *smaller(int *p1, int *p2);int *smaller(int *p1, int *p2);

int main() int *smaller (int *px, int int main() int *smaller (int *px, int *py)*py)

{int a,b,*p;{int a,b,*p; {{

Scanf(“%d %d”,&a, &b);Scanf(“%d %d”,&a, &b); return (*px<*py ? Px : py);return (*px<*py ? Px : py);

P=smaller(&a,&b);P=smaller(&a,&b); } /*smaller*/} /*smaller*/

....

}}

Pointers to Pointers-All our pointers have been Pointers to Pointers-All our pointers have been pointing directly to data. With Advanced Data pointing directly to data. With Advanced Data structuresstructures

• With Advanced Data structures Its often With Advanced Data structures Its often necessary to use pointers that point to other necessary to use pointers that point to other pointerspointers

• Eg - We can have a pointer pointing to pointer Eg - We can have a pointer pointing to pointer to to an integer. an integer.

This 2-level indirection is shown below and This 2-level indirection is shown below and can continue upto many levels of can continue upto many levels of indirectionindirection

/*local declarations*//*local declarations*/

int a,*p,**q;int a,*p,**q;

234560 287650 58

Pointer to integerPointer to Pointer

to integer

integer variable a

397870 234560 287650

/*statements* /*statements* ptop1.c,ptop.c/ptop1.c,ptop.c/

a=58;a=58;

p=&a;p=&a;

q=&p;q=&p;

int **q;int **q;

Printf(“%3d”,a);Printf(“%3d”,a);

Printf(“%3d”,*p);Printf(“%3d”,*p);

Printf(“%3d”,**q);Printf(“%3d”,**q);

int a,*p,**q;int a,*p,**q;

1.1. Each level of indirection require a separate Each level of indirection require a separate indirection operator when it is derefenced.indirection operator when it is derefenced.

2.2. To dereference a pointer using a pointer p, weTo dereference a pointer using a pointer p, we dereference as *p.dereference as *p.3.3. To refer to a, using the pointer q, we have to To refer to a, using the pointer q, we have to

dereference it twice to get the integer a dereference it twice to get the integer a because there are 2 levels of indirections because there are 2 levels of indirections (pointers) involved.(pointers) involved.

int a,*p,**q;int a,*p,**q;

• If we dereference it only once, u are If we dereference it only once, u are referencing p i.e. pointer to integer i.e. q is a referencing p i.e. pointer to integer i.e. q is a pointer to pointer to an integer.pointer to pointer to an integer.

• Double dereference is shown in previous slide .Double dereference is shown in previous slide .

r q p a

Figure-Graphical representation of variables using pointers to pointers

Compatibility - It is important for pointers Compatibility - It is important for pointers to have a type associated with themto have a type associated with them

• They are not just pointer types , but are They are not just pointer types , but are pointers to specific type like integer.pointers to specific type like integer.

• Each pointer takes on attribute of type to Each pointer takes on attribute of type to which it refers in addition to its own attributes.which it refers in addition to its own attributes.

• Now we will see a program to print the size of Now we will see a program to print the size of the pointer and what it refers to.the pointer and what it refers to.

Program Description for size of Program Description for size of pointerpointer

• Note that variables a, c and x are never assigned Note that variables a, c and x are never assigned any values i.e. sizes are independent of the any values i.e. sizes are independent of the values in a variable. i.e. sizes are dependent on values in a variable. i.e. sizes are dependent on type and not on values. type and not on values.

• Size of all ptrs – 4 i.e. size of address in Size of all ptrs – 4 i.e. size of address in program on which it was run.program on which it was run.

• Data Size of the type is the same as size of Data Size of the type is the same as size of pointerpointer

• Check sizeof(px) and sizeof(*px).Check sizeof(px) and sizeof(*px).

Compatibility and Void PointerCompatibility and Void Pointer

• It is invalid to assign a pointer of one type to a It is invalid to assign a pointer of one type to a pointer of another type, even though the value pointer of another type, even though the value in both cases are memory addresses and would in both cases are memory addresses and would hence seem to be fully compatible.hence seem to be fully compatible.

• In C, we can’t use assignment operator with In C, we can’t use assignment operator with pointers to different types, if we try to do we pointers to different types, if we try to do we get a compile error.get a compile error.

• An exception to this is void pointers.An exception to this is void pointers.

• Void pointer is also known as Universal Void pointer is also known as Universal Pointer / Generic Pointer that can be used with Pointer / Generic Pointer that can be used with any pointer.any pointer.

• A void pointer cannot be dereferenced.A void pointer cannot be dereferenced.

• It can be created – void *pVoid;It can be created – void *pVoid;

• We can make explicit assignment between We can make explicit assignment between incompatible pointers types by using a cast.incompatible pointers types by using a cast.

Casting pointer- We can make explicit Casting pointer- We can make explicit assignment between incompatible assignment between incompatible pointers types by using a cast.pointers types by using a cast.• Eg- we can make character pointer p to point to Eg- we can make character pointer p to point to

an integer(a) as shown below- an integer(a) as shown below-int a;int a;char *p;char *p;p=(char *)&a;p=(char *)&a;unless we cast all operations that use p , u unless we cast all operations that use p , u may create greater mounds of garbage. may create greater mounds of garbage.

With With exception of void pointer, pointers should exception of void pointer, pointers should never be castednever be casted

Following statements are valid, but are Following statements are valid, but are extremely dangerous and must be used extremely dangerous and must be used carefully throughout the designcarefully throughout the design

/*local statements*//*local statements*/

Void *pvoid;Void *pvoid;

Char *pchar;Char *pchar;

Int *pintInt *pint

/*statements *//*statements */

Pvoid = pchar;Pvoid = pchar;

Pint = pvoid;Pint = pvoid;

Pint = (int *) pchar;Pint = (int *) pchar;

Construct an example where we have 2 Construct an example where we have 2 variables – 1 int , 1 char. The char has 1 ptr variables – 1 int , 1 char. The char has 1 ptr associated with it, the int has 2, one a second associated with it, the int has 2, one a second level pointer. These vars & their ptrs are level pointer. These vars & their ptrs are shownshown

char c;char c;char *pc;char *pc;int a;int a;int *pa;int *pa;int *ppa;int *ppa;pc=&c;pc=&c;pa=&a;pa=&a;ppa=&pa; ppa=&pa; /*Good & valid pointers*//*Good & valid pointers*/

Fig- pointer compatibilityFig- pointer compatibility

char c;char c; int a; pc=&c;int a; pc=&c;char *pc;char *pc; int *pa; pa=&a;int *pa; pa=&a; int *ppa; ppa=&pa;int *ppa; ppa=&pa;

PcPc cc123450 Z

287870

287650 234560 58

appa pa

287650 234560

/*Invalid pointers will generate errors*//*Invalid pointers will generate errors*/

pc=&a;pc=&a; /*Different types*//*Different types*/

ppa=&a;ppa=&a;/*Different levels*//*Different levels*/

Fig- pointer types must Fig- pointer types must matchmatch a=4; a=4; pa=&a;pa=&a; *pa=4; *pa=4; *ppa=&pa*ppa=&pappa=&pappa=&pa **ppa=4; **ppa=4;

a;a;

*pa; pa;*pa; pa;

**ppa *ppa **ppa *ppa ppappa

intint int

Int * int * int**

Type: int Type: int* Type: int**

a=4*pa=4

**ppa=4pa=&a

*ppa=&pappa=&pa

LVALUE AND RVALUELVALUE AND RVALUE

• In C, an expression is either an l-value or r-value. In C, an expression is either an l-value or r-value. Every expression has a value.Every expression has a value.

• But value in an expression can be used in 2 different But value in an expression can be used in 2 different ways.ways.

1.1. An An lvaluelvalue expression must be used whenever an expression must be used whenever an object is receiving value i.e. it is being modified.object is receiving value i.e. it is being modified.

2.2. An An rvaluervalue expression can be used to supply a value expression can be used to supply a value for further use i.e. to examine or copy its value.for further use i.e. to examine or copy its value.

Lvalue can be only of 7 typesLvalue can be only of 7 typesTable for lvalue expressionsTable for lvalue expressions

Expression typeExpression type CommentsComments

1.1. IdentifierIdentifier Variable identifierVariable identifier

2.2. Expression[…]Expression[…] Array IndexingArray Indexing

3.3. (expression)(expression) Expression must Expression must already be a lvaluealready be a lvalue

4.4. *expression*expression Dereferenced Dereferenced expressionexpression

5.5. Expression.nameExpression.name Structure selectionStructure selection

6.6. Expression->nameExpression->name Structure indirect Structure indirect selectionselection

7.7. Function callFunction call If function uses If function uses return addressreturn address

Examples- for lvalue Examples- for lvalue expressionsexpressions

a = …a = … a[5] =… (a) = … a[5] =… (a) = … *p =…*p =…

Expressions that are not lvalue type are rvalues.Expressions that are not lvalue type are rvalues.

Examples for rvalue expressionsExamples for rvalue expressions

5 5 a+2 a+2 a*6 a*6 a[2]+3a[2]+3 a++a++

Even if an expression is an lvalue, if it is used as Even if an expression is an lvalue, if it is used as

part of larger expression in which operators create part of larger expression in which operators create

Only rvalue expressions, then whole expression is Only rvalue expressions, then whole expression is

an rvaluean rvalue

Example-a[2] is an lvalue. But when it is used in Example-a[2] is an lvalue. But when it is used in

Expression a[2]+3, the whole expression is anExpression a[2]+3, the whole expression is an

rvalue and not an lvalue.rvalue and not an lvalue.

• Similarly in a++, the value of variable a is an Similarly in a++, the value of variable a is an lvalue while whole expression (a++) is an lvalue while whole expression (a++) is an rvaluervalue

Reason to know l and rvalues-Reason to know l and rvalues-

1.1. Some operators need an lvalue as an operand Some operators need an lvalue as an operand

2.2. If we use 1 of these operators and use an If we use 1 of these operators and use an rvalue in the place of operand, then we get a rvalue in the place of operand, then we get a compiler error.compiler error.

Table for Operators that Table for Operators that require lvalue expressionsrequire lvalue expressions

Type of ExpressionType of Expression ExampleExample

Address operatorAddress operator &score&score

Postfix Postfix increment/decrementincrement/decrement

x++; y--;x++; y--;

Prefix Prefix increment/decrementincrement/decrement

++X; --y; ++X; --y;

Assignment(left operand)Assignment(left operand) X=1; y+=3;X=1; y+=3;

Pointer Arithmetic and ArraysPointer Arithmetic and Arrays

• Besides Indexing, Programmers use Besides Indexing, Programmers use another powerful method called Pointer another powerful method called Pointer Arithmetic to move through an array Arithmetic to move through an array from element to element to use in from element to element to use in searching an array sequentially.searching an array sequentially.

Pointers and one-dimensional Pointers and one-dimensional arrayarray

• If a is an array, If a is an array,

then a is constant pointing to the first element in then a is constant pointing to the first element in the array the array

and a+1 is a constant to the second element in and a+1 is a constant to the second element in the array.the array.

• If we have a pointer p, pointing to the second If we have a pointer p, pointing to the second element of the array then p-1 is a pointer to the element of the array then p-1 is a pointer to the previous (first) element and p+1 is a pointer to previous (first) element and p+1 is a pointer to the next (third) element.the next (third) element.

Furthermore, given a, Furthermore, given a, a+2 is the address , 2 elements away from a, a+2 is the address , 2 elements away from a, and a+3 is address , 3 elements from a. and a+3 is address , 3 elements from a.

General Notation – General Notation – Given pointer p, Given pointer p,

p + n is a pointer to the value n elements awayp + n is a pointer to the value n elements awayWhen n is added to a pointer value, we will get aWhen n is added to a pointer value, we will get aValue that correspond to another index location Value that correspond to another index location n elements away.n elements away.n-> offset from original pointer.n-> offset from original pointer.

Figure for Pointer ArithmeticFigure for Pointer Arithmetic

pp

p+1p+1

p+2p+2

p+3p+3

2

4

6

8

a

a+1

a+2

a+3

How to determine the new value ?How to determine the new value ?

• C must know the size of the element that is C must know the size of the element that is identified by the type of pointer.identified by the type of pointer.

Address Calculation FormulaAddress Calculation Formula

address = pointer + (offset * size of element)address = pointer + (offset * size of element)

address = a + n * sizeof (one element))address = a + n * sizeof (one element))

Figure shows result of pointer arithmetic on Figure shows result of pointer arithmetic on different-sized elementsdifferent-sized elements

Int a[3]Int a[3]

aa bb cc

a+1a+1 b+1b+1 c+1c+1

a+2a+2

• Char is implemented as 1 byte Char is implemented as 1 byte

• Int is implemented as 4 bytesInt is implemented as 4 bytes

• Float is implemented as 6 bytes.Float is implemented as 6 bytes.

• a+1 mean different things in different a+1 mean different things in different situations of data types.situations of data types.

• We know how to get address of an array We know how to get address of an array element using a pointer and an offsetelement using a pointer and an offset

Todays TopicsTodays Topics

• 2 prgs demonstrating moving 2 prgs demonstrating moving through arrays using pointersthrough arrays using pointers

• Ptr7.c - printing array forward and Ptr7.c - printing array forward and backward using ptrs.backward using ptrs.

• Function to search with ptrs.Function to search with ptrs.

• binsrch.txt in notepad,ptrs binsrch.txt in notepad,ptrs

• 2-d arrays, Passing Array to a fn2-d arrays, Passing Array to a fn

Pointers and other operatorsPointers and other operators

• Following arithmetic operations are validFollowing arithmetic operations are valid

• P+5, 5+p, p-5, p1-p2, p++ ,--pP+5, 5+p, p-5, p1-p2, p++ ,--p

• p1+p2 not allowed . Adding 2 ptrs is not p1+p2 not allowed . Adding 2 ptrs is not valid in C.valid in C.

• 2 prgs demonstrating moving through arrays 2 prgs demonstrating moving through arrays using pointersusing pointers

• Ptr7.c searching with ptrs.Ptr7.c searching with ptrs.

• binsrch.txt in notepad,ptrs and 2-d arrays, binsrch.txt in notepad,ptrs and 2-d arrays, Passing Array to a fnPassing Array to a fn

Assignment Questions-Assignment Questions-

• Go through the Tips and Programming errors Go through the Tips and Programming errors and Summary given in page 461 and page 462.and Summary given in page 461 and page 462.

• Maintain a separate Assignment Book.Maintain a separate Assignment Book.

• Submit the assignment questions from Submit the assignment questions from Practice set given in Section 9.15 of the Text Practice set given in Section 9.15 of the Text Book from page 463 to page 467 within the Book from page 463 to page 467 within the 24/8/10 at 11a.m.24/8/10 at 11a.m.

Assignment QuestionsAssignment Questions

• Identify the Elementary and Group Identify the Elementary and Group data items in atleast 3 real world data items in atleast 3 real world applications in the form of table applications in the form of table example given in next slide for a example given in next slide for a student studying in a college.student studying in a college.

Application Examples-Application Examples-

• Insurance, RTO, Airline Reservation, Insurance, RTO, Airline Reservation, Railway Reservation, e.t.cRailway Reservation, e.t.c

Student studying in a college Student studying in a college can have following details.can have following details.

1.1. Regno – 5 digit integer – elementary data Regno – 5 digit integer – elementary data itemitem

2.2. Name – array of 10 characters – Group item Name – array of 10 characters – Group item divided into Firstname, middlename and divided into Firstname, middlename and LastnameLastname

3.3. Mks1,mks2,mks3 – integers – elementary Mks1,mks2,mks3 – integers – elementary data item that cannnot be further subdivideddata item that cannnot be further subdivided

RegnoRegno NameName Mks1Mks1 Mks2Mks2 Mks3Mks3

Pointers & 2- d arraysPointers & 2- d arrays

• In 1-d array & 2-d array, the name of In 1-d array & 2-d array, the name of array is a pointer constant to the first array is a pointer constant to the first element of the array.element of the array.

• In 2-d array, the first element is In 2-d array, the first element is another arrayanother array

• Assume a 2-d array of integers. Assume a 2-d array of integers.

• When u dereference a arrayname, we When u dereference a arrayname, we get an array of integersget an array of integers OROR

• Dereferencing of arrayname of a 2-d Dereferencing of arrayname of a 2-d array is a pointer to 1-d array.array is a pointer to 1-d array.

Fig- Pointers to 2-d arrays – Fig- Pointers to 2-d arrays – table[3][4]table[3][4]

table[0] or *(table+0)table[0] or *(table+0)

table[1] or *(table+1)table[1] or *(table+1)

table[2] or *(table+2)table[2] or *(table+2)

C-code for printing the 2-d array - C-code for printing the 2-d array - tabletable

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

{{

for (j=0; j<4; j++)for (j=0; j<4; j++)

printf(“%6d”,(*(*table+i)+j));printf(“%6d”,(*(*table+i)+j));

printf(“\n”);printf(“\n”);

}} /* for i *//* for i */

*(*(table+i)+j) == table[i][j]*(*(table+i)+j) == table[i][j]

Passing an Array to a function-Passing an Array to a function-psaf.cpsaf.c

• Name of an array is a pointer to first element,Name of an array is a pointer to first element,• We can send arrayname to a function for We can send arrayname to a function for

processingprocessing• When we pass an array, we don’t use an When we pass an array, we don’t use an

address operator.address operator.Function Call - doIt(ary); allowedFunction Call - doIt(ary); allowed

- doIt(&ary)- not allowed- doIt(&ary)- not allowed

Arrayname -> address of first element of the Arrayname -> address of first element of the arrayarray

2 ways / notations for 2 ways / notations for declaring a functiondeclaring a function1. Array Notation1. Array Notation 2. 2. Pointer NotationPointer Notationint doIt( int ary[ ]) int doIt( int ary[ ])

User can know that he is dealing with array rather User can know that he is dealing with array rather

Than a single pointer. Advantage from structuredThan a single pointer. Advantage from structured

Programming point of view.Programming point of view.

int doIt(int *arysalary)int doIt(int *arysalary)

U can also declare array in function header as a U can also declare array in function header as a

simple pointer, but this masks data structure (array).simple pointer, but this masks data structure (array).

If u are using multidimensional array, u If u are using multidimensional array, u must use array syntax in the function’s must use array syntax in the function’s header declaration header declaration

• The compiler should know the size of the The compiler should know the size of the dimension after the first to calculate the dimension after the first to calculate the offset for the pointer arithmetic.offset for the pointer arithmetic.

• Hence to receive a 3-d array, use the Hence to receive a 3-d array, use the following declaration in the function following declaration in the function header.header.

float doIt(int bigary[][12][5])float doIt(int bigary[][12][5])

Working of an Array pointer- Working of an Array pointer- Example ProgramExample Program

mainmain

multiplymultiply 5

ary

sizepLastpwalkpary

Program contains several Program contains several points of interest-To see how points of interest-To see how passing array pointer workspassing array pointer works• We have used pointer notation (pary)We have used pointer notation (pary)

• In multiply function definition, we use a In multiply function definition, we use a seperate pointer pwalk to walk through the list.seperate pointer pwalk to walk through the list.

• When the parameter is a pointer, don’t use When the parameter is a pointer, don’t use formal parameter as a variables unless their formal parameter as a variables unless their intent is to change a value in the calling intent is to change a value in the calling programprogram

• We have passed size of array to multiply as We have passed size of array to multiply as parameter, we need to know how much data is parameter, we need to know how much data is to be to be

• We have passed size of array to We have passed size of array to multiply as parameter, we need to multiply as parameter, we need to know how much data is to be processed know how much data is to be processed and use size to calculate address of last and use size to calculate address of last element in the list.element in the list.

Understanding Complex Understanding Complex DeclarationsDeclarations

• Follow right-left-rule to read and Follow right-left-rule to read and understand understand

complex declarationscomplex declarations

start with the identifier in the centre of start with the identifier in the centre of declaration and read the declaration by declaration and read the declaration by alternatively going right and left until u alternatively going right and left until u have read all entities.have read all entities.

Figure in the next slide illustrates thisFigure in the next slide illustrates this

Right – Left rule ConceptRight – Left rule Concept

Identifier

6 4 2 1 3 5 Start

Examples of declarationExamples of declaration

• Consider a simple declarationConsider a simple declaration

int xint x

This is read as x is # an integerThis is read as x is # an integer

since there is nothing on right, we since there is nothing on right, we simply go left. int x # simply go left. int x #

20 1

Pointer Declaration Example – Pointer Declaration Example – read as p is # a pointer # to an read as p is # a pointer # to an integerinteger

int int ** pp ## ##

0 1 324

Keep going right even when there is nothing there until all entities on the left have been exhausted.

Here we have equal no. of entities Here we have equal no. of entities on right and lefton right and left

int int tabletable [4][4]

2 0 1

This is read as table is an array of 4 integers

Regardless of dimensions in array, it is Regardless of dimensions in array, it is considered as 1 element in rule for considered as 1 element in rule for Multi d-arrayMulti d-array

• int int tabletable [4][5][4][5]

2 10

Table is an array of [4][5] integers

#sign is a place holder to show that #sign is a place holder to show that there is no entity to be considered. It is there is no entity to be considered. It is ignored when readignored when read

• Example is difficult and often misread. Example is difficult and often misread. Here we have an array of pointers to Here we have an array of pointers to integers.integers.

int int * aryOfPtrs [5] #* aryOfPtrs [5] #

04 32 1

Read as aryOfPtrs is an array of 5 pointers to # integers diagrammatically shown in next slide.

Fig-a an array of pointers fig-b A Pointer to Fig-a an array of pointers fig-b A Pointer to an arrayan array

aryOfPtrs

Ptr To Ary

Using parentheses, we can change the Using parentheses, we can change the previous example to a pointer to an array of previous example to a pointer to an array of 5 integers. Here the pointer is to whole 5 integers. Here the pointer is to whole array, not just 1 elementarray, not just 1 element

• int (*ptrToAry #) [5]int (*ptrToAry #) [5]

24 0 31

This deal with function declaration. A This deal with function declaration. A simple prototype for a function that simple prototype for a function that returns an integerreturns an integer

• int doIt(…)int doIt(…) int * doIt (int) # int * doIt (int) #

02 1 0 1 3 4 2

Right example shows that doIt is a function that returns a pointer to a # integer

Memory Allocation FunctionsMemory Allocation Functions

• Limitations of First HLLs Limitations of First HLLs

FORTRAN & COBOL- Data structures are always fully FORTRAN & COBOL- Data structures are always fully defined at compile time. If programmers do mistake defined at compile time. If programmers do mistake in selecting & deciding the size of the largest arrays.in selecting & deciding the size of the largest arrays.

• Modern languages like C doesn’t have this limitation Modern languages like C doesn’t have this limitation as they can allocate the size during the run time/ as they can allocate the size during the run time/ execution.execution.

There are 2 ways to reserve memory There are 2 ways to reserve memory locations for an object.locations for an object.

1.1. Static Memory AllocationStatic Memory Allocation

2.2. Dynamic Memory AllocationDynamic Memory Allocation

• SMA-require that declaration and SMA-require that declaration and definition of definition of memory be fully memory be fully specified I the specified I the program. program.

Number of bytes required cannot be Number of bytes required cannot be changed during the run time.changed during the run time.

• SMA works fine as along as u know SMA works fine as along as u know exactly know your memory requirementsexactly know your memory requirements

Dynamic Memory AllocationDynamic Memory Allocation

• DMA – uses predefined functions to allocate DMA – uses predefined functions to allocate and release memory for data, and release memory for data,

while while the program is running. the program is running. - Effectively postpones the data - Effectively postpones the data

definition to runtime. definition to runtime. - To use dynamic memory allocation ,- To use dynamic memory allocation , programmer must use either programmer must use either

standardstandard types or already must havetypes or already must have declared any derived data typesdeclared any derived data types

Figure showing Memory Allocation Figure showing Memory Allocation CharacteristicsCharacteristics

Memory Allocation

StaticUsing declarations &

definitions

Dynamic

Using Predefined functions

Memory Usage – Memory Usage –

4 functions are used with dynamic memory. 4 functions are used with dynamic memory.

3 of them, malloc, calloc and realloc are used 3 of them, malloc, calloc and realloc are used

for memory allocation. 4for memory allocation. 4thth free is used to free is used to

return memory when it is no longer neededreturn memory when it is no longer needed

and all functions are found in (<stdlib.h>) and all functions are found in (<stdlib.h>)

Collection of all these functions are shown in Collection of all these functions are shown in

figure for the next slidefigure for the next slide

Fig- Memory Management Fig- Memory Management FunctionsFunctions

Memory Management

malloc calloc realloc free

Fig- A Conceptual View of MemoryFig- A Conceptual View of Memory

main Called and standard functions

PROGRAM MEMORY

Program heapglobal System stack

DATA MEMORY

MEMORY

Working of Dynamic Memory Working of Dynamic Memory AllocationAllocation

• Conceptually memory is divided into Conceptually memory is divided into 1.1. Program MemoryProgram Memory2.2. Data MemoryData Memory1.1. PM - consists of memory used for PM - consists of memory used for

main and all called functions.main and all called functions.2.2. DM – consists of permanent data DM – consists of permanent data

definitions like global data and definitions like global data and constants, local definitions and constants, local definitions and dynamic data memorydynamic data memory

• Main must be in the memory all the timesMain must be in the memory all the times

• Each called function must be in the Each called function must be in the memory only while it or any of its memory only while it or any of its functions are active. functions are active.

• Most systems keep all functions in Most systems keep all functions in memory while the program is running. memory while the program is running.

• Local variables are available only when it Local variables are available only when it is active only is active only

• More versions of same function can be More versions of same function can be active at a timeactive at a time

• Here multiple copies of local variables are Here multiple copies of local variables are allocated, although only 1 copy of function allocated, although only 1 copy of function is present is present

• Memory Facilities for these capabilities is Memory Facilities for these capabilities is known as stack.known as stack.

• In addition to stack, a memory allocation In addition to stack, a memory allocation called heap is available.called heap is available.

• Heap is unused memory allocated to the program Heap is unused memory allocated to the program and available to be assigned during executionand available to be assigned during execution

• Heap is memory pool from which memory is Heap is memory pool from which memory is allocated when requested by the memory allocated when requested by the memory allocation functions.allocation functions.

• Implementation of memory is upto s/w engineers Implementation of memory is upto s/w engineers who design the system. who design the system.

• Eg- nothing prevents the stack & heap from Eg- nothing prevents the stack & heap from sharing the same pool of memory & is a good sharing the same pool of memory & is a good design concept.design concept.

Memory Allocation Memory Allocation (MALLOC)(MALLOC)• Allocates a block of memory that Allocates a block of memory that

contains no. of bytes specified in its contains no. of bytes specified in its parameter and returns a void pointer to parameter and returns a void pointer to the first byte of the allocated memory i.e the first byte of the allocated memory i.e not initialized.not initialized.

• Hence u should assume that it contains Hence u should assume that it contains garbage and initialize as required by your garbage and initialize as required by your program.program.

• Prototype – void *malloc(size_t size);Prototype – void *malloc(size_t size);

Today’s topicToday’s topic

Parentheses Matching AlgorithmParentheses Matching Algorithm

With an Example verification with With an Example verification with stack.stack.

7-(( x*((x+y)/(j-3))+y) / (4 -2.5))7-(( x*((x+y)/(j-3))+y) / (4 -2.5))0 01 2 2 23 44 4 4 33 44443 2 2 21 1 2 2 2 2 1 00 01 2 2 23 44 4 4 33 44443 2 2 21 1 2 2 2 2 1 0

( ( A + B)( ( A + B) A + B ( A + B (

1 1 1 101 1 1 10 0 0 0 10 0 0 1

) A + B ( - c) A + B ( - c

-1-1-1-1000-1-1-1-1000

2 conditions to hold for a well formed parenthesised 2 conditions to hold for a well formed parenthesised expression in a admissible pattern are expression in a admissible pattern are

1. 1. Parentheses count at end of expression is Parentheses count at end of expression is

0 / No scopes should be left open / No. of 0 / No scopes should be left open / No. of left and right parentheses must be sameleft and right parentheses must be same

2.2. The parenthesis count at each point in The parenthesis count at each point in expression is positive / No right expression is positive / No right parentheses is encountered for which a left parentheses is encountered for which a left parenthesis had not been previously parenthesis had not been previously encountered.encountered.

{ x + ( y - [ a + b ] ) * c - [ ( d + e ) ] } { x + ( y - [ a + b ] ) * c - [ ( d + e ) ] }

/ (h- ( j – ( k – [ l – n] ) ) ) / (h- ( j – ( k – [ l – n] ) ) )

A Stack is used to keep track of types of scopes A Stack is used to keep track of types of scopes encounteredencountered

Whenever a scope opener is encountered , it is pushed into stack.Whenever a scope opener is encountered , it is pushed into stack.

Whenever the scope ender is encountered, the stack is examined. Whenever the scope ender is encountered, the stack is examined.

If the stack is empty, the scope ender does not have a matchingIf the stack is empty, the scope ender does not have a matching

opener and hence the string is invalid.opener and hence the string is invalid.

If , however the stack is not empty, we pop the stack and checkIf , however the stack is not empty, we pop the stack and check

Whether the Popped item corresponds to the scope ender.Whether the Popped item corresponds to the scope ender.

If a match occurs, we continue, else it is invalidIf a match occurs, we continue, else it is invalid

When end of string is reached, the stack must be empty;When end of string is reached, the stack must be empty;

Else one or more scopes must be opened that have not been Else one or more scopes must be opened that have not been closed, and the string is invalid.closed, and the string is invalid.

Algorithm for this procedure is given in next slideAlgorithm for this procedure is given in next slide

Valid = true; /*assume the string is valid*/Valid = true; /*assume the string is valid*/s= the empty stacks= the empty stackwhile ( the entire string is not read) {while ( the entire string is not read) { Read the next symbol (symb) of the string;Read the next symbol (symb) of the string;If ( symb=‘(‘ || symb =‘[’ || symb = ‘{‘) If ( symb=‘(‘ || symb =‘[’ || symb = ‘{‘)

push (s, symb);push (s, symb);If ( symb=‘)‘ || symb =‘]’ || symb = ‘}‘ )If ( symb=‘)‘ || symb =‘]’ || symb = ‘}‘ ) ifif (empty(s))(empty(s))

valid=false;/*string is invalid*/valid=false;/*string is invalid*/ elseelse { { i= pop(s);i= pop(s);

if I is not the matching opener of symbif I is not the matching opener of symbvalid = false;valid = false;}} /*end else*/ /*end else*/ } /* end while */} /* end while */

if ( !empty( s )if ( !empty( s )valid = false;valid = false; if if (valid)(valid) printf(“%s”, The string is valid”);printf(“%s”, The string is valid”); elseelse printf(“%s”, The string is invalid”);printf(“%s”, The string is invalid”);

Union in C- permits a variable Union in C- permits a variable to be interpreted in several to be interpreted in several different waysdifferent ways• Union contain 2 parts – fixed part and Union contain 2 parts – fixed part and

a variable part a variable part

• Fp contain all member declarations Fp contain all member declarations upto the keyword unionupto the keyword union

• VP contain the remainder of the VP contain the remainder of the definition.definition.

• A variable declared of union type T A variable declared of union type T always contain all fixed members of T.always contain all fixed members of T.

Representing Stacks in CRepresenting Stacks in C

Stack - an ordered collection of items: theStack - an ordered collection of items: the

Array.Array.

A stack and an array are entirely A stack and an array are entirely different different

Objects.Objects.

ArrayArray

One end of the array is One end of the array is fixed bottom of the fixed bottom of the stackstack

StackStack

Another field is needed Another field is needed to keep track of top of to keep track of top of stackstack

Can be declared large Can be declared large enough for the enough for the maximum size of the maximum size of the stackstack

Is a dynamic object Is a dynamic object that constantly that constantly changes the size as changes the size as items are pushed and items are pushed and popped.popped.

Size is generally fixed Size is generally fixed and not changedand not changed

But changed But changed constantlyconstantly

Stack in C is declared as a structure containing 2 Stack in C is declared as a structure containing 2 objects 1) Array 2) An integer to indicate the current objects 1) Array 2) An integer to indicate the current top within the arraytop within the array

Stack in C is declared as a structure containing objects Stack in C is declared as a structure containing objects 1) Array 1) Array 2) An integer to indicate the current top within the 2) An integer to indicate the current top within the

array.array.#define STACKSIZE 100#define STACKSIZE 100Struct stackStruct stack {{

int top;int top;int items[STACKSIZE]; int items[STACKSIZE]; };};

STACKSIZE is set to 100 i.e.stack can contain 100STACKSIZE is set to 100 i.e.stack can contain 100Elements (Items[0] through items[99]). Elements (Items[0] through items[99]).

Stack can be also declared to contain floating point Stack can be also declared to contain floating point and character elementsand character elements

Actual stack s may be declared asActual stack s may be declared as

struct stack s;struct stack s;

The empty stack can contain no elements and can The empty stack can contain no elements and can be be

indicated by top=-1.indicated by top=-1.

To initialize the stack to empty state,To initialize the stack to empty state,

s.top=-1; s.top=-1;

To determine whether the stack is empty or notTo determine whether the stack is empty or not

If (s.top=-1) /*stack is empty*/ push(If (s.top=-1) /*stack is empty*/ push(

ElseElse /*stack is not empty*/ /*stack is not empty*/

push(s, i);push(s, i); pop(s)pop(s)

push(struct stack *p, item) pop(struct stack push(struct stack *p, item) pop(struct stack *p)*p)

*p 4*p 4

3 top3 top

22

1 1

Push logic.Push logic.

1.1. Check for the overflow condition.Check for the overflow condition.

2 If stack is filled to max size, full() returns 2 If stack is filled to max size, full() returns true to main() else signal the user of true to main() else signal the user of stack overflow with printf.stack overflow with printf.

3.3. Increment the pointer to point to the Increment the pointer to point to the topmost element in stacktopmost element in stack

4.4. Place the element Place the element

0

1

Pop operationPop operation

Steps- Steps- Check for underflowCheck for underflow

1. If stack is empty with no elements, return 1. If stack is empty with no elements, return true to main(), else do step 2.true to main(), else do step 2.

2. Remove the top element from the stack 2. Remove the top element from the stack then decrement the pointerthen decrement the pointer

3.3. Return this element to the calling programReturn this element to the calling program

0

1

EXAMPLE – INFIX, POSTFIX & PREFIXEXAMPLE – INFIX, POSTFIX & PREFIX

In sum A+B, operator + is applied betweenIn sum A+B, operator + is applied betweenA and B to write sum as A+BA and B to write sum as A+B

Representation -> InfixRepresentation -> Infix

Two other alternate notations to expressTwo other alternate notations to expresssum A+B are sum A+B are

+ AB -> PREFIX + AB -> PREFIX AB + -> POSTFIXAB + -> POSTFIX

Prefixes pre, post and In refer to the relative Prefixes pre, post and In refer to the relative positions w.r.t. operandspositions w.r.t. operands

Notations are easy to use.Notations are easy to use.

Eg- a C function to return the sum of 2 Eg- a C function to return the sum of 2 argumentsarguments

In evaluation of expression, A+B*C is In evaluation of expression, A+B*C is invokedinvoked

by add(A,B). Add operator by add(A,B). Add operator add add precedes precedes thethe

operands A & B.operands A & B.

Additional Egs-Additional Egs-

A+B*C -> is in standard Infix notationA+B*C -> is in standard Infix notation

Multiplication is done before addition andMultiplication is done before addition and

interpreted as A+(B*C).interpreted as A+(B*C).

Multiplication has higher precedence thanMultiplication has higher precedence than

Addition Suppose u want to rewrite A+B*CAddition Suppose u want to rewrite A+B*C

in postfix.in postfix.

Apply rules of precedence and convertingApply rules of precedence and converting

this in stagesthis in stages

Conversion of Infix to PostfixConversion of Infix to Postfix

A+(B*C) -> parentheses for emphasisA+(B*C) -> parentheses for emphasis

A+(BC)* -> convert multiplicationA+(BC)* -> convert multiplication

A(BC*)+ -> convert the additionA(BC*)+ -> convert the addition

ABC*+ -> postfix formABC*+ -> postfix form

The rule to remember during the conversionThe rule to remember during the conversion

process are operations with higher Precedenceprocess are operations with higher Precedence

are converted first and that after the portion ofare converted first and that after the portion of

expression has been converted to postfix is expression has been converted to postfix is treated as a single operand.treated as a single operand.

Rules for conversion from Infix to prefixRules for conversion from Infix to prefix

• Operations with higher precedence are Operations with higher precedence are converted first.converted first.

• After a portion of expression has been converted After a portion of expression has been converted to postfix, it is to be treated as a single operand. to postfix, it is to be treated as a single operand.

Consider the same example with Consider the same example with precedence of operators reversed by the precedence of operators reversed by the deliberate insertion of parenthesesdeliberate insertion of parentheses

(A+B)*C(A+B)*C Infix formInfix form(AB)+*C(AB)+*C Convert the additionConvert the addition(AB)+C*(AB)+C* Convert the MultiplicationConvert the MultiplicationAB+C*AB+C* Postfix FormPostfix Form

Addition is converted before multiplicationAddition is converted before multiplicationbecause of parentheses. because of parentheses. In going from (A+B)*c to (AB)+*C, A and BIn going from (A+B)*c to (AB)+*C, A and Bare operands & * is operator.are operands & * is operator.Rules for converting from Infix to Postfix areRules for converting from Infix to Postfix aresimple Provided u know the order ofsimple Provided u know the order ofprecedenceprecedence

Consider 5 binary operations like addition,Consider 5 binary operations like addition,subtraction, multiplication, division & subtraction, multiplication, division & exponentiationexponentiation

Exponentiation is represented by $. Exponentiation is represented by $.

Value of expression a $ b is a raised to the Value of expression a $ b is a raised to the power of b, power of b,

so that 3 $ 2 so that 3 $ 2

is 3 raised to the power of 2, i.e. 9is 3 raised to the power of 2, i.e. 9

When unparenthesized operators of the When unparenthesized operators of the same precedence are scanned, the order is same precedence are scanned, the order is assumed to be from the left to rightassumed to be from the left to right

Except in case of exponentiation , where theExcept in case of exponentiation , where the

order is assumed from right to left.order is assumed from right to left.

Hence A+B+C means (A+B)+CHence A+B+C means (A+B)+C

A$B$C means A$(B$C)A$B$C means A$(B$C)

By using parentheses, we can override theBy using parentheses, we can override the

default precedence.default precedence.

Convert the following Infix to Postfix Convert the following Infix to Postfix expressionsexpressions

1.1. A+BA+B AB+AB+

2.2. A+B-CA+B-C AB+-CAB+-C

AB+C-AB+C-

3.3. (A+B)*(C-D) (AB)+*(CD)- (A+B)*(C-D) (AB)+*(CD)-

AB+CD-*AB+CD-*

3.3. A$B*C-D+E/F/(G+H)A$B*C-D+E/F/(G+H)

(AB)$*C-D+E/F/(G+H)(AB)$*C-D+E/F/(G+H)

(AB)$C*-D+E/F/(G+H)(AB)$C*-D+E/F/(G+H)

AB$C*-D+ (EF)//(GH)+AB$C*-D+ (EF)//(GH)+

AB$C*D- + (EF)/(GH)+/AB$C*D- + (EF)/(GH)+/

AB$C*D-(EF)(GH)+/+AB$C*D-(EF)(GH)+/+

4.4. ((A+B)*C-(D-E))$(F+G)((A+B)*C-(D-E))$(F+G)

((AB)+*C-(DE)-$(FG)+((AB)+*C-(DE)-$(FG)+

(AB+C*)(DE)--$(FG)+(AB+C*)(DE)--$(FG)+

(AB+C*)(DE)—(FG)+$(AB+C*)(DE)—(FG)+$

A-B/(C*D$E)A-B/(C*D$E)

A- B(C*D$E)/A- B(C*D$E)/

A-B(C*DE$)/*A-B(C*DE$)/*

ABCDE$*/-ABCDE$*/-

Note- Prefix form of Complex expression is Note- Prefix form of Complex expression is not the mirror image of the postfix as seen not the mirror image of the postfix as seen above above

Convert the postfix to prefix form ofConvert the postfix to prefix form of

ExpressionsExpressions

A+(B*C)= A+(BC)*=ABC*+A+(B*C)= A+(BC)*=ABC*+

(A+B)*C=(AB)+*C=AB+C*(A+B)*C=(AB)+*C=AB+C*

There are no parentheses in either of 2There are no parentheses in either of 2

Expressions. The order of operators inExpressions. The order of operators in

postfix expressions determine the actualpostfix expressions determine the actual

Order of operations in evaluatingexpressions ,Order of operations in evaluatingexpressions ,

making use making use

expressions ,making use of parentheses expressions ,making use of parentheses unnecessary.unnecessary.

Evaluating a Postfix ExpressionEvaluating a Postfix ExpressionEach operator in a postfix string refer toEach operator in a postfix string refer toprevious 2 operands in the string ( one ofprevious 2 operands in the string ( one ofthese operands may itself be the result ofthese operands may itself be the result ofapplying a previous operator)applying a previous operator)Suppose that each time read an operand,Suppose that each time read an operand,we push it onto the stack. When we reachwe push it onto the stack. When we reachan operator, its operands will be the top 2 an operator, its operands will be the top 2 Elements on the stack. We can then popElements on the stack. We can then popThese 2 elements , perform the indicated These 2 elements , perform the indicated

Operation on them and push the result on Operation on them and push the result on the stack so that it will be available for use the stack so that it will be available for use as an operand of next operator.as an operand of next operator.

Evaluating a postfix expressionEvaluating a postfix expression

• Define the format of i/p & o/pDefine the format of i/p & o/p• Define routines that depend on mainDefine routines that depend on main• Assume that i/p consists of strings of Assume that i/p consists of strings of

characters, one string per i/p line.characters, one string per i/p line.• End of i/p line is signalled by ‘\n’. Assume End of i/p line is signalled by ‘\n’. Assume

all operands are single-character letters or all operands are single-character letters or digits. O/p is a character string & all single digits. O/p is a character string & all single character operands in initial infix string are character operands in initial infix string are digitsdigits

We use of function called isoperand that We use of function called isoperand that returns true if its argument is an operandreturns true if its argument is an operand

#define MAXCOLS 80#define MAXCOLS 80

main()main()

{{ char infix[MAXCOLS], postfix[MAXCOLS];char infix[MAXCOLS], postfix[MAXCOLS];

While ((infix[pos++] = getchar())!=‘\n’)While ((infix[pos++] = getchar())!=‘\n’)

Infix[--pos]=‘\0’;Infix[--pos]=‘\0’;

Printf(“%s”,”original infix expression is”,infix);Printf(“%s”,”original infix expression is”,infix);

Postfix(infix, postr);Postfix(infix, postr);

Printf(“%s\n”,postr);Printf(“%s\n”,postr);

}} /*end main*//*end main*/

Opndstk= empty stackOpndstk= empty stack

/*scan the input string reading one element at a time /*scan the input string reading one element at a time in symb*/in symb*/

While (not end of the input)While (not end of the input) {{

symb=next input character;symb=next input character;

If (symb is an operand)If (symb is an operand)

push (opndstk, symb);push (opndstk, symb);

ElseElse {/*symbol is an operator*/{/*symbol is an operator*/

Opnd2=pop(opndstk);Opnd2=pop(opndstk);

Opnd1=pop(opndstk);Opnd1=pop(opndstk);

Value=result of applying symb to opnd1 & opnd2;Value=result of applying symb to opnd1 & opnd2;

Push (opndstk, value);Push (opndstk, value);

}/*end else*/}/*end else*/

Return (pop(opndstk));Return (pop(opndstk));

Evaluate following postfix expressionEvaluate following postfix expression

6 2 3 + - 3 8 2 / + * 2 $ 3 +6 2 3 + - 3 8 2 / + * 2 $ 3 +

SymbSymb Opnd1Opnd1 Opnd2Opnd2 ValueValue opndstkopndstk

66 66

22 6,26,2

33 6,2,36,2,3

++ 22 33 55 6,56,5

SymbSymb Opnd1Opnd1 Opnd2Opnd2 ValueValue opndstkopndstk

-- 66 55 11 11

33 66 55 11 1,31,3

88 66 55 11 1,3,81,3,8

22 66 55 11 1,3,8,21,3,8,2

SymbSymb Opnd1Opnd1 Opnd2Opnd2 ValueValue opndstkopndstk

// 88 22 44 1,3,41,3,4

++ 33 44 77 1,71,7

** 11 77 77 77

22 11 77 77 7,27,2

SymbSymb Opnd1Opnd1 Opnd2Opnd2 ValueValue opndstopndstkk

$$ 77 22 4949 4949

33 77 22 4949 49,349,3

++ 4949 33 5252 5252

Algorithm to convert an infix string without parentheses into a postfix string. We see for precedence

Converting Infix to Postfix NotationConverting Infix to Postfix Notation

Consider infix Expressions A+B*C & Consider infix Expressions A+B*C & (A+B)*C and their respective expressions(A+B)*C and their respective expressionsABC*+ and AB+C*. The order of operandsABC*+ and AB+C*. The order of operandsis the same as in original expression. is the same as in original expression. In the first case, * precedes the + operatorIn the first case, * precedes the + operatorAnd in second case, closing parentheses + isAnd in second case, closing parentheses + isforced to precede the * operator. Precedence forced to precede the * operator. Precedence

playplayan important role in transforming infix to postfixan important role in transforming infix to postfixexpressionexpression

We read an Infix expression, evaluate it by first We read an Infix expression, evaluate it by first converting it into postfix expressionconverting it into postfix expression

Expressions within the innermost parentheses Expressions within the innermost parentheses must be converted to postfix so that they can bemust be converted to postfix so that they can betreated as single operands. Parentheses can betreated as single operands. Parentheses can besuccessively eliminated until the entire expressionsuccessively eliminated until the entire expressionis converted. The last pair to be opened within ais converted. The last pair to be opened within agroup of parentheses enclose the first expressiongroup of parentheses enclose the first expressionwithin that group to be transformed.within that group to be transformed.

Assume the existence of a functionAssume the existence of a functionprcd(op1,op2) where op1 & op2 are prcd(op1,op2) where op1 & op2 are characters representing operators.characters representing operators.

This function returns TRUE if op1 hasThis function returns TRUE if op1 has

precedence over op2 when op1 appears toprecedence over op2 when op1 appears to

the left of op2 in an infix expression withoutthe left of op2 in an infix expression without

Parentheses and returns FALSE otherwise.Parentheses and returns FALSE otherwise.

Eg- prcd(‘*’ , ’+’) are TRUE , whereas Eg- prcd(‘*’ , ’+’) are TRUE , whereas prcd(‘+’,’*’) is FALSE.prcd(‘+’,’*’) is FALSE.

Portions for I TestPortions for I Test

Pointers- Unit-1, Stack-Unit-3Pointers- Unit-1, Stack-Unit-3

Lab ProgramsLab Programs

1,2,4,51,2,4,5

Opndstk = the empty stackOpndstk = the empty stack

While (not end of input)While (not end of input) {{

Symb = next input character;Symb = next input character;

if (symb is an operand)if (symb is an operand)

add symb to postfix stringadd symb to postfix string

elseelse {{

while (!while (!empty(opstk)&&prcd(stacktop(opstk),symb))empty(opstk)&&prcd(stacktop(opstk),symb))

{ topsymb = pop(opstk);{ topsymb = pop(opstk);

add topsymb to postfix string; }/*while*/add topsymb to postfix string; }/*while*/push(opstk, symb);push(opstk, symb); }}}}

While (!empty(opstk))While (!empty(opstk)) {{

Topsymb= pop(opstk);Topsymb= pop(opstk);

Add topsymb to postfix string;Add topsymb to postfix string;

}} /*end while*//*end while*/

• Pointers unit-1,stack unit-2Pointers unit-1,stack unit-2

• Lab prgms-1,2,4,5Lab prgms-1,2,4,5