Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Pointers Every Computer has addressable memory locations. Identifiers are assigned to data and their contents are manipulated."— Presentation transcript:

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

2 Example In a C program, we can have void main() {int a,b;/*variable is assigned a a=3;value & manipulated, printf(“%d”,a,&a); & is called ampersand */ a=5;b=a;printf(“%u”,b,&b);}

3 A Pointer is a derived datatype A Pointer is a derived datatype It is a data type built from one of the standard types i.e. int, float, char, double It is a data type built from one of the standard types i.e. int, float, char, double Pointer’s value is any of the addresses available in the computer for storing and accessing the data Pointer’s value is any of the addresses available in the computer for storing and accessing the data Pointers are built on the concept of pointer constants or addresses Pointers are built on the concept of pointer constants or addresses

4 Fig - Character constants & variables

5 We can have a Character constant i.e any letter of the alphabet that can be drawn from universe of all characters A Character constant can be a value and stored In a variable say ‘G’ stored in achar, a variable given by the programmer. In 1 MB of computer’s memory, imagine 145600 to be a memory location in which character constant ‘G’ is stored.

6 A Program define 2 pointers and print their addresses as pointers #include /*prg to print character */ int main()/*addresses*/ { char a,b; printf(“%p %p\n”,&a,&b); return 0; }

7

8 To access a variable through a ptr p, code int *p,a; p=&a *->indirection operator *->indirection operator Indirection is a unary operator Indirection is a unary operator Indirection and address operators are inverse of each other Indirection and address operators are inverse of each other

9 Initialization Of Pointer Variables C Language doesn’t initialize variables. C Language doesn’t initialize variables. If at all it initializes, it is done by the system loader. If at all it initializes, it is done by the system loader. Hence when we start our program, all of our uninitialized variables have unknown garbage in them. Hence when we start our program, all of our uninitialized variables have unknown garbage in them. An OS clears the memory when it loads a program which cant be counted especially with programs that run on multiple systems An OS clears the memory when it loads a program which cant be counted especially with programs that run on multiple systems

10 Figure-Uninitialized pointers-such errors are difficult to debug because it is delayed till program execution ? ? a p int a; int *p; Some garbage: Unknown value Different garbage: Pointer to unknown value

11 To correct the problem, always assign a valid address to the pointer. To correct the problem, always assign a valid 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 are declared and defined. Dv should be defined before the pointer variable. Its also possible initialize pointers when they are declared and defined. Dv should be defined before the pointer variable.

12 Pointers 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 is through return value. Only direct way to send something back from a udf function 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 variable. When we pass by address, we pass the pointer to the variable. When we use pass by value method, the data is exchanged in the called function, but nothing changes in the calling function. We see unworkable & workable exchange programs xchg.c, xchg1.c When we use pass by value method, the data is exchanged in the called function, but nothing changes in the calling function. We see unworkable & workable exchange programs xchg.c, xchg1.c

13 Pass By value 7 57 5 a b temp 5 No Change x y Exchanged

14 Rather than pass values of 2 to be exchanged, we could pass pointer to the values 1 To exchange using pointers, create pointers using the address operator in the function call. xchg( &a, &b); xchg( &a, &b); 2.To use pass by address, the formal parameters in the called function 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. This allows us to access data in the calling program using call by address. This allows us to access data in the calling program using call by address. When we need to return more than 1 value from a function, we can use pointers When we need to return more than 1 value from a function, we can use pointers

15 7 &a 8 &b temp 5 After Exchange

16 Functions Returning Pointers We can have a function from returning a pointer to a calling function We can have a function from returning a pointer to a calling function As an Example, u have a program to find smaller of 2 variables. We pass 2 pointers to the function that uses a conditional expression to determine which value is smaller As an Example, u have a program to find smaller of 2 variables. We pass 2 pointers to the function that uses a conditional expression to determine which value is smaller Return value is the address of smallest no. as a pointer. Return value is the address of smallest no. as a pointer.

17 Example for Function returning pointers. Prototype declaration int *smaller(int *p1, int *p2); int main() int *smaller (int *px, int *py) {int a,b,*p;{ Scanf(“%d %d”,&a, &b);return (*px<*py ? Px : py); P=smaller(&a,&b);} /*smaller*/..}

18 Pointers to Pointers-All our pointers have been pointing directly to data. With Advanced Data structures With Advanced Data structures Its often necessary to use pointers that point to other pointers With Advanced Data structures Its often necessary to use pointers that point to other pointers Eg - We can have a pointer pointing to pointer to an integer. Eg - We can have a pointer pointing to pointer to an integer.

19 This 2-level indirection is shown below and can continue upto many levels of indirection /*local declarations*/ int a,*p,**q; 23456028765058 Pointer to integer Pointer to Pointer to integer integer variable a 397870 234560287650

20 /*statements* ptop1.c,ptop.c/ a=58;p=&a;q=&p; int **q; Printf(“%3d”,a);Printf(“%3d”,*p);Printf(“%3d”,**q);

21 int a,*p,**q; 1.Each level of indirection require a separate indirection operator when it is derefenced. 2.To dereference a pointer using a pointer p, we dereference as *p. dereference as *p. 3.To refer to a, using the pointer q, we have to dereference it twice to get the integer a because there are 2 levels of indirections (pointers) involved.

22 int a,*p,**q; If we dereference it only once, u are referencing p i.e. pointer to integer i.e. q is a pointer to pointer to an integer. If we dereference it only once, u are referencing p i.e. pointer to integer i.e. q is a pointer to pointer to an integer. Double dereference is shown in previous slide. Double dereference is shown in previous slide. rqpa Figure-Graphical representation of variables using pointers to pointers

23 Compatibility - It is important for pointers to have a type associated with them They are not just pointer types, but are pointers to specific type like integer. They are not just pointer types, but are pointers to specific type like integer. Each pointer takes on attribute of type to which it refers in addition to its own attributes. Each pointer takes on attribute of type to which it refers in addition to its own attributes. Now we will see a program to print the size of the pointer and what it refers to. Now we will see a program to print the size of the pointer and what it refers to.

24 Program Description for size of pointer Note that variables a, c and x are never assigned any values i.e. sizes are independent of the values in a variable. i.e. sizes are dependent on type and not on values. Note that variables a, c and x are never assigned any values i.e. sizes are independent of the values in a variable. i.e. sizes are dependent on type and not on values. Size of all ptrs – 4 i.e. size of address in program on which it was run. Size of all ptrs – 4 i.e. size of address in program on which it was run. Data Size of the type is the same as size of pointer Data Size of the type is the same as size of pointer Check sizeof(px) and sizeof(*px). Check sizeof(px) and sizeof(*px).

25 Compatibility and Void Pointer It is invalid to assign a pointer of one type to a pointer of another type, even though the value in both cases are memory addresses and would hence seem to be fully compatible. It is invalid to assign a pointer of one type to a pointer of another type, even though the value in both cases are memory addresses and would hence seem to be fully compatible. In C, we can’t use assignment operator with pointers to different types, if we try to do we get a compile error. In C, we can’t use assignment operator with pointers to different types, if we try to do we get a compile error. An exception to this is void pointers. An exception to this is void pointers.

26 Void pointer is also known as Universal Pointer / Generic Pointer that can be used with any pointer. Void pointer is also known as Universal Pointer / Generic Pointer that can be used with 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 incompatible pointers types by using a cast. We can make explicit assignment between incompatible pointers types by using a cast.

27 Casting pointer- We can make explicit assignment between incompatible pointers types by using a cast. Eg- we can make character pointer p to point to an integer(a) as shown below- Eg- we can make character pointer p to point to an integer(a) as shown below- int a; char *p; p=(char *)&a; unless we cast all operations that use p, u may create greater mounds of garbage. With exception of void pointer, pointers should never be casted

28 Following statements are valid, but are extremely dangerous and must be used carefully throughout the design /*local statements*/ Void *pvoid; Char *pchar; Int *pint /*statements */ Pvoid = pchar; Pint = pvoid; Pint = (int *) pchar;

29 Construct an example where we have 2 variables – 1 int, 1 char. The char has 1 ptr associated with it, the int has 2, one a second level pointer. These vars & their ptrs are shown char c; char *pc; int a; int *pa; int *ppa; pc=&c;pa=&a; ppa=&pa; /*Good & valid pointers*/ Fig- pointer compatibility

30 char c;int a; pc=&c; char *pc;int *pa; pa=&a; int *ppa; ppa=&pa; Pcc 123450 Z 287870 28765023456058 appa pa 287650234560

31 /*Invalid pointers will generate errors*/ pc=&a;/*Different types*/ ppa=&a;/*Different levels*/

32 Fig- pointer types must match a=4;pa=&a; *pa=4;*ppa=&pa ppa=&pa **ppa=4; a; a; *pa; pa; *pa; pa; **ppa *ppa ppa **ppa *ppa ppa int Int * int * int** Type: intType: int*Type: int** a=4 *pa=4 **ppa=4 pa=&a *ppa=&pa ppa=&pa

33 LVALUE AND RVALUE In C, an expression is either an l-value or r-value. Every expression has a value. In C, an expression is either an l-value or r-value. Every expression has a value. But value in an expression can be used in 2 different ways. But value in an expression can be used in 2 different ways. 1. An lvalue expression must be used whenever an object is receiving value i.e. it is being modified. 2. An rvalue expression can be used to supply a value for further use i.e. to examine or copy its value.

34 Lvalue can be only of 7 types Table for lvalue expressions Expression type Comments 1.Identifier Variable identifier 2.Expression[…] Array Indexing 3.(expression) Expression must already be a lvalue 4.*expression Dereferenced expression 5.Expression.name Structure selection 6.Expression->name Structure indirect selection 7. Function call If function uses return address

35 Examples- for lvalue expressions a = … a[5] =… (a) = …*p =… Expressions that are not lvalue type are rvalues. Examples for rvalue expressions 5 a+2 a*6 a[2]+3a++

36 Even if an expression is an lvalue, if it is used as part of larger expression in which operators create Only rvalue expressions, then whole expression is an rvalue Example-a[2] is an lvalue. But when it is used in Expression a[2]+3, the whole expression is an rvalue and not an lvalue.

37 Similarly in a++, the value of variable a is an lvalue while whole expression (a++) is an rvalue Similarly in a++, the value of variable a is an lvalue while whole expression (a++) is an rvalue Reason to know l and rvalues- 1. Some operators need an lvalue as an operand 2. If we use 1 of these operators and use an rvalue in the place of operand, then we get a compiler error.

38 Table for Operators that require lvalue expressions Type of Expression Example Address operator &score Postfix increment/decrement x++; y--; Prefix increment/decrement ++X; --y; Assignment(left operand) X=1; y+=3;

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

40 Pointers and one-dimensional array If a is an array, If a is an array, then a is constant pointing to the first element in the array and a+1 is a constant to the second element in the array. If we have a pointer p, pointing to the second element of the array then p-1 is a pointer to the previous (first) element and p+1 is a pointer to the next (third) element. If we have a pointer p, pointing to the second element of the array then p-1 is a pointer to the previous (first) element and p+1 is a pointer to the next (third) element.

41 Furthermore, given a, a+2 is the address, 2 elements away from a, and a+3 is address, 3 elements from a. General Notation – Given pointer p, p + n is a pointer to the value n elements away When n is added to a pointer value, we will get a Value that correspond to another index location n elements away. n-> offset from original pointer.

42 Figure for Pointer Arithmetic p p+1 p+1 p+2 p+2 p+3 p+3 2 4 6 8 a a+1 a+2 a+3

43 How to determine the new value ? C must know the size of the element that is identified by the type of pointer. C must know the size of the element that is identified by the type of pointer. Address Calculation Formula Address Calculation Formula address = pointer + (offset * size of element) address = pointer + (offset * size of element) address = a + n * sizeof (one element))

44 Figure shows result of pointer arithmetic on different-sized elements Int a[3] abc a+1b+1c+1 a+2

45 Char is implemented as 1 byte Char is implemented as 1 byte Int is implemented as 4 bytes Int is implemented as 4 bytes Float is implemented as 6 bytes. Float is implemented as 6 bytes. a+1 mean different things in different situations of data types. a+1 mean different things in different situations of data types. We know how to get address of an array element using a pointer and an offset We know how to get address of an array element using a pointer and an offset

46 Todays Topics 2 prgs demonstrating moving through arrays using pointers 2 prgs demonstrating moving through arrays using pointers Ptr7.c - printing array forward and backward using ptrs. Ptr7.c - printing array forward and 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 fn 2-d arrays, Passing Array to a fn

47 Pointers and other operators Following arithmetic operations are valid Following arithmetic operations are valid P+5, 5+p, p-5, p1-p2, p++,--p P+5, 5+p, p-5, p1-p2, p++,--p p1+p2 not allowed. Adding 2 ptrs is not valid in C. p1+p2 not allowed. Adding 2 ptrs is not valid in C. 2 prgs demonstrating moving through arrays using pointers 2 prgs demonstrating moving through arrays using pointers Ptr7.c searching with ptrs. Ptr7.c searching with ptrs. binsrch.txt in notepad,ptrs and 2-d arrays, Passing Array to a fn binsrch.txt in notepad,ptrs and 2-d arrays, Passing Array to a fn

48 Assignment Questions- Go through the Tips and Programming errors and Summary given in page 461 and page 462. Go through the Tips and Programming errors and Summary given in page 461 and page 462. Maintain a separate Assignment Book. Maintain a separate Assignment Book. Submit the assignment questions from Practice set given in Section 9.15 of the Text Book from page 463 to page 467 within the 24/8/10 at 11a.m. Submit the assignment questions from Practice set given in Section 9.15 of the Text Book from page 463 to page 467 within the 24/8/10 at 11a.m.

49 Assignment Questions Identify the Elementary and Group data items in atleast 3 real world applications in the form of table example given in next slide for a student studying in a college. Identify the Elementary and Group data items in atleast 3 real world applications in the form of table example given in next slide for a student studying in a college. Application Examples- Insurance, RTO, Airline Reservation, Railway Reservation, e.t.c Insurance, RTO, Airline Reservation, Railway Reservation, e.t.c

50 Student studying in a college can have following details. 1.Regno – 5 digit integer – elementary data item 2.Name – array of 10 characters – Group item divided into Firstname, middlename and Lastname 3.Mks1,mks2,mks3 – integers – elementary data item that cannnot be further subdivided RegnoNameMks1Mks2Mks3

51 Pointers & 2- d arrays In 1-d array & 2-d array, the name of array is a pointer constant to the first element of the array. In 1-d array & 2-d array, the name of array is a pointer constant to the first element of the array. In 2-d array, the first element is another array In 2-d array, the first element is another array Assume a 2-d array of integers. Assume a 2-d array of integers. When u dereference a arrayname, we get an array of integersOR When u dereference a arrayname, we get an array of integersOR Dereferencing of arrayname of a 2-d array is a pointer to 1-d array. Dereferencing of arrayname of a 2-d array is a pointer to 1-d array.

52 Fig- Pointers to 2-d arrays – table[3][4] table[0] or *(table+0) table[1] or *(table+1) table[2] or *(table+2)

53 C-code for printing the 2-d array - table for (i=0; i<3; i++) { for (j=0; j<4; j++) printf(“%6d”,(*(*table+i)+j));printf(“\n”); }/* for i */ *(*(table+i)+j) == table[i][j]

54 Passing an Array to a function- psaf.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 processing We can send arrayname to a function for processing When we pass an array, we don’t use an address operator. When we pass an array, we don’t use an address operator. Function Call - doIt(ary); allowed - doIt(&ary)- not allowed - doIt(&ary)- not allowed Arrayname -> address of first element of the array

55 2 ways / notations for declaring a function 1. Array Notation 2. Pointer Notation int doIt( int ary[ ]) User can know that he is dealing with array rather Than a single pointer. Advantage from structured Programming point of view. int doIt(int *arysalary) U can also declare array in function header as a simple pointer, but this masks data structure (array).

56 If u are using multidimensional array, u must use array syntax in the function’s header declaration The compiler should know the size of the dimension after the first to calculate the offset for the pointer arithmetic. The compiler should know the size of the dimension after the first to calculate the offset for the pointer arithmetic. Hence to receive a 3-d array, use the following declaration in the function header. Hence to receive a 3-d array, use the following declaration in the function header. float doIt(int bigary[][12][5])

57 Working of an Array pointer- Example Program mainmultiply 5 ary size pLast pwalkpary

58 Program contains several points of interest-To see how passing array pointer works We have used pointer notation (pary) We have used pointer notation (pary) In multiply function definition, we use a seperate pointer pwalk to walk through the list. In multiply function definition, we use a seperate pointer pwalk to walk through the list. When the parameter is a pointer, don’t use formal parameter as a variables unless their intent is to change a value in the calling program When the parameter is a pointer, don’t use formal parameter as a variables unless their intent is to change a value in the calling program We have passed size of array to multiply as parameter, we need to know how much data is to be We have passed size of array to multiply as parameter, we need to know how much data is to be

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

60 Understanding Complex Declarations Follow right-left-rule to read and understand Follow right-left-rule to read and understand complex declarations complex declarations start with the identifier in the centre of declaration and read the declaration by alternatively going right and left until u have read all entities. Figure in the next slide illustrates this

61 Right – Left rule Concept Identifier 642 135 Start

62 Examples of declaration Consider a simple declaration Consider a simple declaration int x This is read as x is # an integer This is read as x is # an integer since there is nothing on right, we simply go left. int x # 201

63 Pointer Declaration Example – read as p is # a pointer # to an integer int *p## 013 24 Keep going right even when there is nothing there until all entities on the left have been exhausted.

64 Here we have equal no. of entities on right and left int table[4] 201 This is read as table is an array of 4 integers

65 Regardless of dimensions in array, it is considered as 1 element in rule for Multi d-array int table[4][5] int table[4][5] 21 0 Table is an array of [4][5] integers

66 #sign is a place holder to show that there is no entity to be considered. It is ignored when read Example is difficult and often misread. Here we have an array of pointers to integers. Example is difficult and often misread. Here we have an array of pointers to integers. int * aryOfPtrs [5] # 04 3 21 Read as aryOfPtrs is an array of 5 pointers to # integers diagrammatically shown in next slide.

67 Fig-a an array of pointers fig-b A Pointer to an array aryOfPtrs Ptr To Ary

68 Using parentheses, we can change the previous example to a pointer to an array of 5 integers. Here the pointer is to whole array, not just 1 element int (*ptrToAry #) [5] int (*ptrToAry #) [5] 2 4 0 31

69 This deal with function declaration. A simple prototype for a function that returns an integer int doIt(…)int * doIt (int) # int doIt(…)int * doIt (int) # 02101 3 42 Right example shows that doIt is a function that returns a pointer to a # integer

70 Memory Allocation Functions Limitations of First HLLs Limitations of First HLLs FORTRAN & COBOL- Data structures are always fully defined at compile time. If programmers do mistake in selecting & deciding the size of the largest arrays. Modern languages like C doesn’t have this limitation as they can allocate the size during the run time/ execution. Modern languages like C doesn’t have this limitation as they can allocate the size during the run time/ execution.

71 There are 2 ways to reserve memory locations for an object. 1. Static Memory Allocation 2. Dynamic Memory Allocation SMA-require that declaration and definition of memory be fully specified I the program. SMA-require that declaration and definition of memory be fully specified I the program. Number of bytes required cannot be changed during the run time. SMA works fine as along as u know exactly know your memory requirements SMA works fine as along as u know exactly know your memory requirements

72 Dynamic Memory Allocation DMA – uses predefined functions to allocate and release memory for data, while the program is running. DMA – uses predefined functions to allocate and release memory for data, while the program is running. - Effectively postpones the data definition to runtime. - Effectively postpones the data definition to runtime. - To use dynamic memory allocation, - To use dynamic memory allocation, programmer must use either standard programmer must use either standard types or already must have types or already must have declared any derived data types declared any derived data types

73 Figure showing Memory Allocation Characteristics Memory Allocation Static Using declarations & definitions Dynamic Using Predefined functions

74 Memory Usage – 4 functions are used with dynamic memory. 3 of them, malloc, calloc and realloc are used for memory allocation. 4 th free is used to return memory when it is no longer needed and all functions are found in ( ) Collection of all these functions are shown in figure for the next slide

75 Fig- Memory Management Functions Memory Management malloc calloc reallocfree

76 Fig- A Conceptual View of Memory main Called and standard functions PROGRAM MEMORY Program heapglobalSystem stack DATA MEMORY MEMORY

77 Working of Dynamic Memory Allocation Conceptually memory is divided into Conceptually memory is divided into 1.Program Memory 2.Data Memory 1.PM - consists of memory used for main and all called functions. 2.DM – consists of permanent data definitions like global data and constants, local definitions and dynamic data memory

78 Main must be in the memory all the times Main must be in the memory all the times Each called function must be in the memory only while it or any of its functions are active. Each called function must be in the memory only while it or any of its functions are active. Most systems keep all functions in memory while the program is running. Most systems keep all functions in memory while the program is running. Local variables are available only when it is active only Local variables are available only when it is active only

79 More versions of same function can be active at a time More versions of same function can be active at a time Here multiple copies of local variables are allocated, although only 1 copy of function is present Here multiple copies of local variables are allocated, although only 1 copy of function is present Memory Facilities for these capabilities is known as stack. Memory Facilities for these capabilities is known as stack. In addition to stack, a memory allocation called heap is available. In addition to stack, a memory allocation called heap is available.

80 Heap is unused memory allocated to the program and available to be assigned during execution Heap is unused memory allocated to the program and available to be assigned during execution Heap is memory pool from which memory is allocated when requested by the memory allocation functions. Heap is memory pool from which memory is allocated when requested by the memory allocation functions. Implementation of memory is upto s/w engineers who design the system. Implementation of memory is upto s/w engineers who design the system. Eg- nothing prevents the stack & heap from sharing the same pool of memory & is a good design concept. Eg- nothing prevents the stack & heap from sharing the same pool of memory & is a good design concept.

81 Memory Allocation (MALLOC) Allocates a block of memory that contains no. of bytes specified in its parameter and returns a void pointer to the first byte of the allocated memory i.e not initialized. Allocates a block of memory that contains no. of bytes specified in its parameter and returns a void pointer to the first byte of the allocated memory i.e not initialized. Hence u should assume that it contains garbage and initialize as required by your program. Hence u should assume that it contains garbage and initialize as required by your program. Prototype – void *malloc(size_t size); Prototype – void *malloc(size_t size);

82 Today’s topic Parentheses Matching Algorithm With an Example verification with stack.

83 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 0 ( ( A + B)A + B ( 1 1 1 100 0 0 1 1 1 1 100 0 0 1 ) A + B ( - c -1-1-1-1000 -1-1-1-1000

84 2 conditions to hold for a well formed parenthesised expression in a admissible pattern are 1. Parentheses count at end of expression is 0 / No scopes should be left open / No. of left and right parentheses must be same 2.The parenthesis count at each point in expression is positive / No right parentheses is encountered for which a left parenthesis had not been previously encountered.

85 { x + ( y - [ a + b ] ) * c - [ ( d + e ) ] } / (h- ( j – ( k – [ l – n] ) ) ) { x + ( y - [ a + b ] ) * c - [ ( d + e ) ] } / (h- ( j – ( k – [ l – n] ) ) )

86 A Stack is used to keep track of types of scopes encountered Whenever a scope opener is encountered, it is pushed into stack. Whenever the scope ender is encountered, the stack is examined. If the stack is empty, the scope ender does not have a matching opener and hence the string is invalid. If, however the stack is not empty, we pop the stack and check Whether the Popped item corresponds to the scope ender. If a match occurs, we continue, else it is invalid When end of string is reached, the stack must be empty; Else one or more scopes must be opened that have not been closed, and the string is invalid. Algorithm for this procedure is given in next slide

87 Valid = true; /*assume the string is valid*/ s= the empty stack while ( the entire string is not read) { Valid = true; /*assume the string is valid*/ s= the empty stack while ( the entire string is not read) { Read the next symbol (symb) of the string; If ( symb=‘(‘ || symb =‘[’ || symb = ‘{‘) push (s, symb); If ( symb=‘)‘ || symb =‘]’ || symb = ‘}‘ ) if(empty(s)) if(empty(s)) valid=false;/*string is invalid*/ valid=false;/*string is invalid*/ else{ i= pop(s); else{ i= pop(s); if I is not the matching opener of symb valid = false; }/*end else*/ } /* end while */ if ( !empty( s ) valid = false; if (valid) if (valid) printf(“%s”, The string is valid”); printf(“%s”, The string is valid”); else else printf(“%s”, The string is invalid”); printf(“%s”, The string is invalid”);

88 Union in C- permits a variable to be interpreted in several different ways Union contain 2 parts – fixed part and a variable part Union contain 2 parts – fixed part and a variable part Fp contain all member declarations upto the keyword union Fp contain all member declarations upto the keyword union VP contain the remainder of the definition. VP contain the remainder of the definition. A variable declared of union type T always contain all fixed members of T. A variable declared of union type T always contain all fixed members of T.

89 Representing Stacks in C Stack - an ordered collection of items: the Array. Array. A stack and an array are entirely different A stack and an array are entirely differentObjects.

90 Array One end of the array is fixed bottom of the stack Stack Another field is needed to keep track of top of stack Can be declared large enough for the maximum size of the stack Is a dynamic object that constantly changes the size as items are pushed and popped. Size is generally fixed and not changed But changed constantly

91 Stack in C is declared as a structure containing 2 objects 1) Array 2) An integer to indicate the current top within the array Stack in C is declared as a structure containing objects 1) Array 2) An integer to indicate the current top within the array. array. #define STACKSIZE 100 Struct stack{ int top; int items[STACKSIZE]; }; STACKSIZE is set to 100 i.e.stack can contain 100 Elements (Items[0] through items[99]).

92 Stack can be also declared to contain floating point and character elements Actual stack s may be declared as struct stack s; The empty stack can contain no elements and can be indicated by top=-1. To initialize the stack to empty state, s.top=-1; To determine whether the stack is empty or not If (s.top=-1) /*stack is empty*/ push( Else/*stack is not empty*/

93 push(s, i);pop(s) push(struct stack *p, item) pop(struct stack *p) *p 4 3 top 3 top 2 1

94 Push logic. 1.Check for the overflow condition. 2 If stack is filled to max size, full() returns true to main() else signal the user of stack overflow with printf. 3.Increment the pointer to point to the topmost element in stack 4.Place the element 0 1

95 Pop operation Steps- Check for underflow 1. If stack is empty with no elements, return true to main(), else do step 2. 2. Remove the top element from the stack then decrement the pointer 3.Return this element to the calling program 0 1

96 EXAMPLE – INFIX, POSTFIX & PREFIX In sum A+B, operator + is applied between A and B to write sum as A+B Representation -> Infix Two other alternate notations to express sum A+B are + AB -> PREFIX AB + -> POSTFIX

97 Prefixes pre, post and In refer to the relative positions w.r.t. operands Notations are easy to use. Eg- a C function to return the sum of 2 arguments In evaluation of expression, A+B*C is invoked In evaluation of expression, A+B*C is invoked by add(A,B). Add operator add precedes the by add(A,B). Add operator add precedes the operands A & B. operands A & B.

98 Additional Egs- A+B*C -> is in standard Infix notation Multiplication is done before addition and interpreted as A+(B*C). Multiplication has higher precedence than Addition Suppose u want to rewrite A+B*C in postfix. Apply rules of precedence and converting this in stages

99 Conversion of Infix to Postfix A+(B*C) -> parentheses for emphasis A+(BC)* -> convert multiplication A(BC*)+ -> convert the addition ABC*+ -> postfix form The rule to remember during the conversion process are operations with higher Precedence are converted first and that after the portion of expression has been converted to postfix is treated as a single operand.

100 Rules for conversion from Infix to prefix Operations with higher precedence are converted first. Operations with higher precedence are converted first. After a portion of expression has been converted to postfix, it is to be treated as a single operand. After a portion of expression has been converted to postfix, it is to be treated as a single operand.

101 Consider the same example with precedence of operators reversed by the deliberate insertion of parentheses (A+B)*CInfix form (AB)+*CConvert the addition (AB)+C*Convert the Multiplication AB+C*Postfix Form Addition is converted before multiplication because of parentheses. In going from (A+B)*c to (AB)+*C, A and B are operands & * is operator. Rules for converting from Infix to Postfix are simple Provided u know the order of precedence

102 Consider 5 binary operations like addition, subtraction, multiplication, division & exponentiation Exponentiation is represented by $. Value of expression a $ b is a raised to the power of b, so that 3 $ 2 is 3 raised to the power of 2, i.e. 9

103 When unparenthesized operators of the same precedence are scanned, the order is assumed to be from the left to right Except in case of exponentiation, where the order is assumed from right to left. Hence 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 the default precedence.

104 Convert the following Infix to Postfix expressions 1. A+BAB+ 2. A+B-CAB+-C AB+C- 3.(A+B)*(C-D) (AB)+*(CD)- AB+CD-*

105 3.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+ (EF)//(GH)+ AB$C*D- + (EF)/(GH)+/ AB$C*D-(EF)(GH)+/+

106 4.((A+B)*C-(D-E))$(F+G) ((AB)+*C-(DE)-$(FG)+(AB+C*)(DE)--$(FG)+(AB+C*)(DE)—(FG)+$

107 A-B/(C*D$E) A- B(C*D$E)/ A-B(C*DE$)/*ABCDE$*/-

108 Note- Prefix form of Complex expression is not the mirror image of the postfix as seen above Convert the postfix to prefix form of Expressions A+(B*C)= A+(BC)*=ABC*+ (A+B)*C=(AB)+*C=AB+C* There are no parentheses in either of 2 Expressions. The order of operators in postfix expressions determine the actual Order of operations in evaluatingexpressions, making use

109 expressions,making use of parentheses unnecessary. Evaluating a Postfix Expression Each operator in a postfix string refer to previous 2 operands in the string ( one of these operands may itself be the result of applying a previous operator) Suppose that each time read an operand, we push it onto the stack. When we reach an operator, its operands will be the top 2 Elements on the stack. We can then pop These 2 elements, perform the indicated

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

111 Evaluating a postfix expression Define the format of i/p & o/p Define the format of i/p & o/p Define routines that depend on main Define routines that depend on main Assume that i/p consists of strings of characters, one string per i/p line. Assume that i/p consists of strings of characters, one string per i/p line. End of i/p line is signalled by ‘\n’. Assume all operands are single-character letters or digits. O/p is a character string & all single character operands in initial infix string are digits End of i/p line is signalled by ‘\n’. Assume all operands are single-character letters or digits. O/p is a character string & all single character operands in initial infix string are digits

112 We use of function called isoperand that returns true if its argument is an operand #define MAXCOLS 80 main() {char infix[MAXCOLS], postfix[MAXCOLS]; While ((infix[pos++] = getchar())!=‘\n’) Infix[--pos]=‘\0’; Printf(“%s”,”original infix expression is”,infix); Postfix(infix, postr); Printf(“%s\n”,postr); }/*end main*/

113 Opndstk= empty stack /*scan the input string reading one element at a time in symb*/ While (not end of the input){ symb=next input character; If (symb is an operand) push (opndstk, symb); Else{/*symbol is an operator*/ Opnd2=pop(opndstk);Opnd1=pop(opndstk); Value=result of applying symb to opnd1 & opnd2; Push (opndstk, value); }/*end else*/ Return (pop(opndstk));

114 Evaluate following postfix expression 6 2 3 + - 3 8 2 / + * 2 $ 3 +

115 SymbOpnd1Opnd2Valueopndstk 66 26,2 36,2,3 +2356,5

116 SymbOpnd1Opnd2Valueopndstk -6511 36511,3 86511,3,8 26511,3,8,2

117 SymbOpnd1Opnd2Valueopndstk /8241,3,4 +3471,7 *1777 21777,2

118 SymbOpnd1Opnd2Valueopndstk $724949 3724949,3 +4935252 Algorithm to convert an infix string without parentheses into a postfix string. We see for precedence

119 Converting Infix to Postfix Notation Consider infix Expressions A+B*C & (A+B)*C and their respective expressions ABC*+ and AB+C*. The order of operands is the same as in original expression. In the first case, * precedes the + operator And in second case, closing parentheses + is forced to precede the * operator. Precedence play an important role in transforming infix to postfix expression

120 We read an Infix expression, evaluate it by first converting it into postfix expression Expressions within the innermost parentheses must be converted to postfix so that they can be treated as single operands. Parentheses can be successively eliminated until the entire expression is converted. The last pair to be opened within a group of parentheses enclose the first expression within that group to be transformed.

121 Assume the existence of a function prcd(op1,op2) where op1 & op2 are characters representing operators. This function returns TRUE if op1 has precedence over op2 when op1 appears to the left of op2 in an infix expression without Parentheses and returns FALSE otherwise. Eg- prcd(‘*’, ’+’) are TRUE, whereas prcd(‘+’,’*’) is FALSE.

122 Portions for I Test Pointers- Unit-1, Stack-Unit-3 Lab Programs 1,2,4,5

123 Opndstk = the empty stack While (not end of input){ Symb = next input character; if (symb is an operand) add symb to postfix string else{ while (!empty(opstk)&&prcd(stacktop(opstk),symb)) { topsymb = pop(opstk); add topsymb to postfix string; }/*while*/ push(opstk, symb);}} add topsymb to postfix string; }/*while*/ push(opstk, symb);}}

124 While (!empty(opstk)){ Topsymb= pop(opstk); Add topsymb to postfix string; }/*end while*/

125 Pointers unit-1,stack unit-2 Pointers unit-1,stack unit-2 Lab prgms-1,2,4,5 Lab prgms-1,2,4,5


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

Similar presentations


Ads by Google