 Good morning everybody and welcome back to this session on pointers. I will also discuss few important things for the workshop projects. I propose to describe the way projects were conducted in a programming course here and perhaps you might take a cue from that. At first what we wish to discuss in this session is the notion of pointers. So, we will begin by re looking at addresses and values and then we will define the notion of a pointer. So, we will look at the notion of a pointer, pointer variables, pointer assignments, pointer arithmetic and then we see an example program. In particular, we will discuss the importance of pointers in C C plus plus programming languages for parameter passing in functions. We will take an example of a simple problem of swapping numbers. Finally, in this session I propose to discuss another problem that problem is of separating name strings which have been given as input. All of these relate to the use of pointers. So, let us begin the discussion on pointers itself. First of all, the memory we have seen that the memory consists of locations and each location has a unique address. Actually, these addresses internally inside a computer start with 0. So, you have a 0th location, first location, second location etcetera etcetera and they typically go all the way to the 2th power 32. So, that is actually called an address space. To give you a simile, suppose you have houses in a colony and houses are given 3 digit numbers. So, what is the maximum number of distinct houses that you can address? Well, one house can be number 0, 1, 2, 3 etcetera up to 990. In decimal system 3 digit number means 999 is maximum, smallest is 0 and I am talking only of positive numbers because we are talking about house numbers not of integer values. Just as 3 digit number can uniquely address 990 or 1000 houses in a locality. Similarly, in binary system 32 bit numbers can uniquely address 2 to the power 32 unique memory locations. I am talking about address not about what is contained inside a memory location. Typically, the smallest unit of memory location is a byte and most of the machines are called byte addressable machines. Participating teachers might have read in the books the notion of a word, half word, word boundaries etcetera etcetera. I find it pretty confusing to introduce that to a students of a programming course. So, what we can do instead? Because all machines by the way independent of their hardware capabilities, if a c compiler is ported on to those machines then c compiler requires that memory be addressable at the level of a byte. However, we note that for numerical values such as float or integer or something, we cannot fit our values in 8 bits as we have seen and therefore, typically we would require 2, 4 or 8 bytes depending upon whether you have a short value, whether you have a long value or you have a double float whatever. Consider the following. Consider int float and care variable and arrays such as these int m float a 3 care c 4. Let us assume that these have been assigned some values this is in our program. Now, when we write such a declaration in our program and say m equal to something a 0 equal to something a 1 equal to something etcetera, these values go and set inside the allocated locations. Let us look at those locations a bit more carefully. So, here are these locations. The locations let us presume that the first location assigned is 10,000, next location assigned is 10,004, next location assigned is 10,008. Why are these locations differing by 4? Remember that in our c compiler typically an integer or a float would be allocated 4 bytes and therefore, if the first byte for the value of m starts at 10,000, then second byte is 10,001, third byte is 10,002, fourth byte is 10,003. So, 10,000 to 10,003 all these 4 bytes will be allocated to hold the value of m which happens to be let us say 573 and therefore, next memory available for allocation is only 10,004. What we are seeing is we might expect the addresses to be allocated in this fashion. It is not necessary we do not know by the way whether if we declare the variables in this order, then whether the memory will be allocated in exactly increasing order of the appearance of the next. We do not know that yet. We will examine that, but we expect that this is not the reason to explain. Consequently, we have here the address 10,000 and the next 3 bytes holding the value 573, the address 10,004 and next 3 bytes holding the value of the 0th element of array which let us say happens to be 673.852 etcetera, etcetera and so on. Notice that c is a care array. A care array every element has only one byte because it represents one character code. I have shown it by saying that the 0th element holds you, next element holds n, next element holds i etcetera. So, we have uniques as a four letter word occupying bytes 10,000, 16, 10,000, 17, 10,000, 18, 10,000, 19. Notice the difference is only one in addresses here because each consecutive byte will hold only one value. So, it does not require more than one byte to hold a value. This will generally be then the addressing scheme for a hopeful allocation of our variables in arrays to memory. So far, so good. Now, these addresses are essentially pointers. What do they do? They point to a specific location containing value of a specific type. So, for example, the value 10,000 is a pointer to m. In bracket, I have written that type of value it points to. This has great significance when we discuss the notion of pointer in the programming language. Similarly, the value 10,000, 16 is a pointer to a 2 that is second element and this is a pointer to a float type of value. 10,000, 21 is a pointer to c 1 first element of c which is a care type of value. You will recall from the previous slide that these were the addresses pointing to these variables or array elements as we had seen earlier. Why do we bother about these addresses? So, here is the important observation. Ordinarily, we have nothing to do with these pointers or absolute addresses. Why should we worry? We use variable names and array elements in our program and whenever we use a variable name say m, we imply by m its value let us say 573 or whatever. Whenever we say c 1 in our program, we imply by it the value character u which is head inside that by. So, as well we are concerned as programmers, our life is limited to looking at variable names, array elements which represent values of specific type, integer, float, care, whatever. And that is perfectly happy and comfortable situation for us. However, programming languages such as c and c plus plus and some others provide the facility to use these pointers directly within a program. Why would they do so? Well, when c programming language was written as I mentioned to you earlier those were the days when these high level programming languages were being used to write compilers and even operating systems. It was necessary in writing these pieces of system software that you should be able to manipulate addresses directly and that perhaps is the reason why pointers were explicitly introduced. If you see the object oriented paradigm which is most popular today implemented by java programming language, java explicitly denies you the access to these actual pointers and there are pitfalls which I will explain what happens. However, since c and c plus plus provide for the pointers, it is important for our students to know what these pointers are, where they must be used and where they ought not to be used. So coming back then we are talking about addresses which point to the locations which hold some values. Ordinarily we have nothing to do with these addresses, but the programming language permits us to actually handle these addresses directly. To do this we have to declare spatial variables. These variables are called pointer variables in our programs. This is an example given int star p1. If I said int p1, p1 would become an ordinary variable which will hold actual integer value. But when I say int star p1, I am actually referring to a new type of variable which is called a pointer variable and which is capable of holding an absolute address. That is the objective of putting this star here. So when I say int star p1, we are declaring a variable of type pointer, it cannot hold any value. However, it can hold an address which points to a value and it points to a specific type of value int. So as I was saying p1 is a pointer variable, it cannot hold a value but it can hold a pointer and it can hold a pointer or it can hold the address of a location which can contain only integer value. There is a reason for this distinction. If I have a float star p2, p2 is another pointer which can hold an address but it can point only to a floating point value. Care star p3, p3 is a pointer which can hold an address but it can point to a only character type of value. Now you will understand the distinction. If p1 is a pointer which points to integer type of values, then the addresses have to be in multiple of 4 because each integer value address begins, let us say at 10000, the next address will begin at 100004, next address will begin at 100008 itself. Whereas character variables, the addresses will be consecutive memory locations. So if at all you want to move the address from one value to another, you have to move it in the increment which is commensurate with the amount of space that a particular type of variable takes and therefore the addresses have this binding to a type. What about p1, p2, p3 themselves? As I said p1, p2, p3 are special memory locations allocated in our program only. They will not contain a value but they are allocated separate memory locations. Each one can contain an address which itself is typically a 32-bit number and can represent an address from 0 to 2 to the power 31 minus 1. Suppose we now write our program in our program, m was an integer variable if you recall, m was given a value 573. If I say p1 is equal to AND m, this AND is a point address operator. If I write only m, it means the value of m. If I write AND m, ampersand m, then this combination is a deadly combination. It means address of m. So this is important to understand and to emphasize to our students that whenever I use a variable name, it stands for the value contained inside that variable but whenever I precede it by ampersand, then this combination stands for the address of the variable. Now if m has the value 573, then p1 will be assigned what value? Will p1 get the value of m? What value will it be assigned? Let us see. p1 will be assigned the value 10000. Look at the address where m was located. This comes from the first line. So m had a value 573 alright but m we presumed was allocated 4 bytes starting with address 10000. Therefore 10000 is the address of m. This 10000 address is what will be the value of p1. Just as p1 is being assigned the address of m by AND m. There could be, there is a corresponding reverse operation called dereferencing. This is address operator. This is a dereferencing operator which is star, the one which we saw in the declaration. If I say star p1, then star refers to the value pointed by p1 and that is why this is a perfectly legitimate expression where I declare q to be a integer value and say q equal to star p1. Please note p1 is a pointer and therefore can never be assigned, its value can never be assigned to an integer variable. However what is being assigned is not the value of p1 but the value pointed to by p1. That is why we say star p1. So this will assign to q what? You can guess correctly. This will assign 573 which was the value which was actually pointed to by p1. How it pointed to by p1? Because p1 was assigned the value 10000. So p1 had this value and star p1 is the value pointed to by p1 which is 573. This then is the crux of usage of pointers. In a nutshell pointers are special type of variables. They do not hold any conventional value as integer, character, float but they hold addresses. The addresses can be assigned to them by finding out the address of any variable or array element by using the AND operator. It must be noted that the addresses only of the right kind can be assigned to pointers and what do we mean by right kind? If m is integer then p1 must be declared as pointer to integer. If some z is character then p3 must be declared as pointer to character if p3 is to be assigned address of z. Once I assign a pointer a value then it contains this address as its value and then later on to any integer variable I assign the value pointed to by this pointer star p1. It will assign to cube 573. We notice that AND is called the address operator which calculates the address of a memory location. Star is called dereferencing operator that means it is always applied to a pointer and then when we say star any pointer then actually star plus that pointer combination refers to the value pointed to by pointer. Can we actually manipulate the pointer values knowing that their addresses? The answer is yes. For example we can print the actual value of m by saying output star p1. So instead of saying output m I can say output star p1 if p1 has been allocated the address of a memory. This will print 573. As I said we can also print the value of a pointer. The address stored there will be printed. For example see out p1. This is a perfectly valid statement. Please note however we have no control over the absolute values contained in this pointer. Why? Because the pointers cannot be inputted. We cannot give input value to a pointer. Pointers get their values only by assignment to an address of a variable. We only declare variables and array elements. So whenever I said p1 is equal to and m or and something then only a pointer gets a value and what value it gets? It gets the value which the compiler has assigned to the storage location containing that variable. For example see out p1 may print something like this. O X B F D E 4 1 A 0. Those of you are familiar with hexadecimal system will remember that this is just as we write decimal numbers or binary numbers. This is an hexadecimal number. The way to write an hexadecimal number is to precede the number by 0 X. X that is for hexadecimal. So all hexadecimal numbers typically are written as 0 X something. And what is that something? Any combination of digits between 0 to F. 0 1 2 3 4 5 6 7 8 line A B C D E F. So you see here B F D E 4 1 A 0 or is the address hexadecimal. It is interesting to note that if you run the same program again and again and print such a pointer value after assigning it appropriately, you will not necessarily get the same result. Why? Because every time when the compiler compiles the program and the program is loaded by the operating system or execution, the actual addresses may be different. It depends upon what memory is available at that point in time at the operating system level and what memory gets allocated to our program. But within one program execution, the addresses will remain fixed for the entire execution of the program. Another thing, we can as I said we can assign addresses to all point this should be and A 0. That is because I am actually assigning the address of A 0 to P 2. Notice that array A was float and the address of A is being assigned to the pointer P 2. Now after having said that I can also say P 2 plus plus. Please note what has happened P 2 has got an address of this type. In our terms let us say it has got an address of 1004. Now 1004 I am saying increment that value P 2 by 1 P 2 plus plus or P 2 plus 1. Curiously this will not increment the contents of P 2 by 1 but rather by the number of bytes allocated to the associated type. That is why it is important to associate a pointer with a type of value. So since P 2 was declared to be float, when I say P 2 plus plus the pointer will increase its internal content from 10000 to 10000 4. If I now say c out star P 2 it will actually print the value of A 1. Why? Because A 1 happens to be the next element hopefully allocated sequentially after A 0 leaving a gap of 4 bytes for A 0. So A 0, A 1, A 2, A 3, etcetera, etcetera their addresses will differ by 4 bytes. But to point to those addresses if I have a pointer which contains the address of first element or for that matter any one element. When I increment that pointer this is by the way equivalent of saying P 2 is equal to P 2 plus 1. It will be wrong to say P 2 is equal to P 2 plus 4 or P 2 is equal to P 2 plus 1. We always increment or decrement a pointer by 1. In fact we can add any number to P 1 or P 2 but it is not that number by which the address is moved inside. It is moved by that number multiplied by the number of bytes allocated for that type and that is why the association of pointer with that type is important. Let us explain these through a some example. Here is a small program segment written int main int m and a 3 I have just declared one integer array and m and n as integer variables m is equal to 573, n is equal to minus 1, 2, 3, 4, 5, 6, 7. In this particular program segment I am not doing anything with a. So, let us concentrate of m n on m and n. I am declaring two integer pointers star PTR 1 and star PTR 2. I am saying C out m and n. So, I now get the printed of values of m and n. m and n have been assigned these values. So, I expect to get these values. Now, look at what I mean. I assign the address of m to PTR 1. So, PTR 1 is an integer pointer no problem. Then I assign to value PTR 2 which is equal to PTR 1 plus 1. If PTR 1 has the address of m, then PTR 1 plus 1 will have the address of 4 bytes after the address of m. So, PTR 2 will be 4 bytes removed from PTR 1. Since I have declared m and n one after another, I expect PTR 2 to point to the value of n. Consequently, I do the following. I first print the pointers PTR 1 and PTR 2 and then I print the corresponding data values pointed to by them. I print star PTR 1 and star PTR 2 which I hope to find m and n. I am very sure of m because I have explicitly assigned the address of m to PTR 1. I hope that PTR 2 points to n. Let us see what happens when I execute this algorithm. C plus plus pointer example 1 dot c p p dot slash a dot out. I get 573 n minus 1 2 3 4 5 6 7 as the values of m and n. The pointers have values these. What are these values? 0 x b f c a f a c 0 x b f c a f a b 0. Notice that in extra decimal, the next value after a c will be a d then a e then a f and then b 0. Much like the decimal system except the digits are up to f. So, that means this address is exactly 4 bytes away from this address. What it confirms? Whenever I add 1 to pointer 1, the value that I generate is 4 away from the previous line. But the corresponding data values that I get are 573 and some value minus 1077 21707. What is this? This is not the value of n. My value of n was this. So, why we are not getting the right value of n? If I run this program again, I will get these values as same because these I am printing as the m and n value. The pointer values may be different depending upon the pointer allocated the address allocated to m. This one will always be 4 bytes away from this because I am explicitly adding 4 or adding 1 to the pointer here. However, the corresponding data values may be 573 and something else and that something else will actually be the value, an integer value pointed to by this address. Which address? This address. Very clearly this does not appear to be the address of n. So, let us try something else. I modify the program. Now also I have star ptr1 star ptr2. I assign the values to m and n. I output the value of m and n. But now I am more careful. I take the address of m, assign it to ptr1. Then I say and n, assign it to ptr1. So, I am explicitly finding out the address of m and n and assigning it to these two pointers. Now, I will print these two pointers and the corresponding data values. Let us see what do we get after this modification. If I compile this program again and execute, first of all look at the pointers. The first pointer ends at 2c. The next pointer ends at 28. 28 is not 4 bytes larger than 2c. In fact, it is smaller. After 28 you have 29, 2a, 2b. Very clearly n has been allocated an address earlier than m. Well, that is compiled as prerogative. But notice the corresponding data values that I get are correct data values. Why? Because I have explicitly calculated the address of n by saying and n and then assigned it to ptr2. What is the moral of the story? The moral of the story is at least as far as simple variables are concerned. Even if I have declared those simple variables in a specific sequence in my source program, there is absolutely no guarantee that they will be allocated consecutive locations in the memory by the compiler. Compiler is free to allocate them anywhere. Does the same thing happen with array? Because if it does, then we might lose a very interesting possibility of using pointers with arrays. Fortunately, it does not happen that way. Let us see what happens in case of an array. So here is another example. I have m and a3. This is the same program by the way. This time instead of emphasizing m and n, I am saying a0 is 573. a1 is minus 1, 2, 3, 4, 5, 6, 7 and a2 is 94. In short, I am allocating values to three elements of array. I will print these out just for confirmation. Now I am doing an interesting thing. I am saying get the address of a0 and after finding out the address, put it in ptr1. Then I am saying increment ptr1 by 1 and put it into ptr1. Then I am saying add 2 to ptr1 and put it in ptr3. Notice we know from our previous discussion that when I say ptr2 is equal to ptr plus 1, the actual address of ptr1 will be incremented by 4 bytes and that value will be added and put here. Similarly, when I say ptr1 plus 2, it means two integer locations away from this address. So actually 8 bytes will be added to the actual address and that will be assigned to ptr1. I am doing something similar which I tried with m and n. I added to the pointer of m1 and expected it to point to n. It did not. Here also I am trying the same thing. Let us see what happens. The pointers have values ptr1 and ptr2 and ptr3. The data values are star ptr1, star ptr2, star ptr3. So I am just trying to see what happens now here. Look at the results. The execution results, these are the values printed for a0, a1, a2. The pointers have these values and the corresponding data values are 573 minus 1, 2, 3, 4, 5, 6, 7 and 94. Exactly the same values that I had assigned to three elements of value. So a very important thing we know. Irrespective of how the compiler allocates memory to simple variables, we are guaranteed by the C programming language that in case of arrays, the memory locations allotted are always consecutive. That means if we increment a pointer by one, points to the next successive element of the array. Consequently, we can actually keep incrementing a pointer and keep accessing the array elements. So instead of setting up a for loop like for i equal to 0, semicolon i less than n, semicolon i plus plus and then say a i something. I could also do the following. I could assign a pointer p and take it the address of a0 and then when I move this inside the iteration if I simply say star in bracket p plus i. Notice that p plus i will mean the first element, second element, third element being pointed to. So this is an interesting speaker that you can do. You can try some exercises from any one of the standard textbooks to illustrate this point to your students. Next we consider the problem of passing parameters to function. We have seen these earlier. So far we have seen parameters passed as values to the functions. Now we note that the only thing that we get back is a single value which the function returns. That is the notion of a function in mathematics f of x comma y comma z whatever whatever will return a single value which is assigned to a left hand side variable. So here is an example. Some function which is being computed which is let us say 5 x plus y modulo 10 some arbitrary function. There are two integer parameters x and y using them the value of f is calculated. There is another error here my God. What should be the return? Well if I am calculating. So if we use this function in our program we may use it like this in a, b, c, c in a and b and c is equal to f of a plus b. So what happens when we do this? What happens when we do this is very simple. The control goes let us go back control goes back with the values of a and b to this function. The value of a is transferred to x value of b is transferred to y. Using these two it calculates some it is not exactly addition. So some is not a right word. We may use some other word. It calculates the value of this function as 5 x plus y modulo 10. Now we confirm that with respect to the number of parameters that we pass we get back only one value. Here is the problem with this approach. What if we need to get back more than one value upon return? What if we want to calculate five different values in that function and return back all the five? There appears to be no mechanism because there is only one return statement that return statement can return one value of whatever type you have declared that function to be. That is our notion of function. However, knowing that there is absolutely no other way of executing some separately written code except to call it as a function. Then I seem to be stymied because I do not want to be limited by this. Let us examine to confirm that this is indeed the case because what I expect is look I have passed some parameters. You have done some computations and given back me one value. But I hope just as you took parameters from me I hope to get back those parameters from you. So in case those parameters were modified in the function why should they not reflect back on me? So here is an example of if I want to swap values of x and y simple integer variables. What do I do to swap values? Basically x is 5, y is 10 let us say. I want to make x 10 and y is 5. I need a temporary variable. I need the values of x and y and I execute a simple series of assignment statement. Temp equal to x, x equal to y, y equal to 10. Very standard. And now when I print out x and y they will have exactly the swap value. Very simple. Now suppose I want to write a swap function and I write it like this int swap, int p, int q then int temp, temp t for temporary and then I said t equal to p, p equal to q, q equal to 2 return 0. If I call this function, if I call this function using the indicated thing int x, y input x and y instead of putting the swap code there I say swap x, y and I now print x and y. Notice that what I am doing I am sending x and y to that function. I hope that when let us go back to the previous slide for a moment I hope that when my values of x and y come into p and q here and when this program executes then p and q are swapped here. Then I expect that when I say return 0 apart from sending back the value it should also put back the values of p and q into my variables. Unfortunately it does not do that because when we invoke the function swap the values of x and y are copied and sent to the function. Even if the function swaps these the change is not reflected in the original value since those values are not copied back. So, we note that if a parameter value is passed the value does not come back. This by the way is termed technically as passing parameters by value. So, we take the value copy it and give it after the computations the return value comes but the parameter values do not come back that is the impact of passing parameters by value. Obviously this is not acceptable to us can we do something else well this is where the pointers help us. Let us see how the pointers help us. So, here is the program which does not work I have repeated that program but return it properly void try to swap int a int b call by value int temp equal to a equal to b b equal to temp return int main x is equal to 1 y equal to 2 try to swap x y and output x and y. You will find that when you execute the program x and y were 1 and 2 and x and y will remain 1 and 2 this program is nothing but the consolidation of various program segment that we saw. This is the proper program with a function name parameters and the function being called here only one thing is not worthy here we are saying void something we had this discussion earlier also what is the purpose of void. Notice that after declaring this void when I say return I am not putting any value to be return such is the case when I am writing a function which is not required to calculate a result and return it to me I do not expect a result actually I expect that function to modify my parameters and send them back to me that is all I am trying to do here I am sending the parameters x and y to a and b and expecting them back. I do not care of the function returning any value because the function is not computing any return ever value and that in all such cases when you do not expect function to return any result value you will always term it as void. So, just as you have types integer float in float double care whatever whatever there is a special type called void. Void means of no type actually it is an indicator that this function will never attempt to return a specific result value that is why you say void int main this this this program we said does not work because it passes parameters by values values of x and y again we emphasize or pass to the function try to swap these values are assigned to local variables a and b updated values do not get copied back here I have added an explanation for void which is typically used when the function is not required or expected to return any now we come to the most important point we would like the values of parameters to come back we have occasions when we have to write functions when whatever that function does we want to get the values back consider for example I have an array of thousand numbers and I want to sort it I can write a sort algorithm inside my main program, but since I may require to sort different arrays it is better to write a single function to sort an array what will be the parameter given to that function the array itself all elements of the array have to go there now that function will rearrange those elements wouldn't it be funny that if I send these array elements to a function called sort it actually sorts those elements which are copied values of the original array and then it does not return the things back to me I still am left with the original it is not useful in general then what happens when I want the parameters also to be returned back what cc plus plus provides for is that if you want the parameters to be returned back what you should do is you should pass a pointer to these values so instead of mentioning x and y as parameters in our main program if we said address of x and address of y and if that is what was passed then the computations in the function will not be done on the copies of the values which are given but on the original locations themselves and therefore whatever computations are done in the function they will reflect back onto the original so here is the key statement if we need to get back the modified values of variable parameters back in the calling program variables are arranged it does not matter what we should pass their pointers that way the function refers to original locations of these variables which were allocated in the calling program thus modifying their contents so let us see the impact here is a program that works void swap and int and a int and b called by reference int main int x equal to 1 y equal to 2 swap x y notice that I have used parameters x and y but the corresponding parameters are pointer to a and pointer to an int and another pointer consequently what she does is that instead of taking the value contained in x and y it calculates the address of x and gives it to a address of y and gives it to b so these are the two pointers and a and b now when I say int a a equal to b b equal to temp a and b are integer variables by the so I am saying receive the addresses of the corresponding variables then now I do temp equal to a equal to b b equal to temp these operations will not be done on copied values but will be directly done on the corresponding variables x and y because their addresses have come back to since I am referring to the original addresses while passing the parameters and working on the parameters such a function call is said to be called by reference and this will swap the numbers correct so notice the way I write I write my parameters normally as I do in my function reference but here I say and a and b so I am putting an address of a and address of b I am in fact using the point of it I mentioned whether it is variables or arrays the call by reference is a preferred method however there is one difference c language and c plus plus of course is very funny for variables it will ordinarily pass variables by value if you want to pass them by reference you have to say and a and b for every corresponding variable whether it is integer photo but for array if I pass an array name in my parameter then the array is always passed by a point so if there is a corresponding array name not address of array because there is no notion of address of an array address of one element of an array makes it the array name itself actually is a pointer to the first element of the array so corresponding array element in my function a corresponding array in my function as a parameter will always be passed by reference never by value consequently whatever function we write if arrays are parameters then I will always get the results back from the return values of the app in another 10 minutes I would like to discuss so I hope you have understood the pointer thing you can actually solve a lot of problems using pointers particularly on arrays and particularly character arrays in this particular program I wish to explain by choosing a sort of realistic problem how the character pointers are used in case of string handling I you will recall that strings in C are stored in character arrays terminated by a null character so here is a problem suppose we have prepared a text file of names of people as per this list say Nandlalshwara Mureshwar Pujare Deepak Phatak Millen Soni Ajit Diwan these instantly are the names of all my colleagues here as they are I mean arbitrarily selected out of about 40 colleagues anyway now what we wish to do these are lines by the way so this is one line of input this second line of input third line of input there are either blanks or new line character here what I have done I have prepared a list there may be 100 names 500 names million names whatever what we wish to do is read each line in a character array in our program and separate out the first and last names storing these in two separate character so we will look at the problem of reading just one line one string from a line separating out first name and separating out second first problem how do I read a line we have not yet studied scan f and print f by the way C in is not directly useful in when I say C in C in is actually as I said is an is an object class operator so what it does is C in when I say C in it will read individual values so I can I can assign values suppose I want to give values to m and n I can say C in m and m comma m less less n greater greater n and it will read two values from the same line so in a single line I can have five values I can have three values it will read as many lines as it is but now I want to read the whole line itself I do not care what it contains I presume that it contains two names separated by one or more blanks but I want to read the entire string n a n d l a l blank s a r d a may be blank blank and then new line character I want to read all of this there is a function in C library called get s or get string what it does is it reads an entire line up to the new line character that means up to end of line including that end of line it takes that whole string whatever be its length then it removes that last character new line character replaces it with backslash 0 which is the null character and puts all of this in the array let us look at a program which does this using get string function and subsequently let us look at the logic by which the names are separated the first name and last name are separated program is called first last name dot c p p it can be easily converted into a C program just because I am using c out for example I am not using c in here but I am using c out and I cannot compile that without c p p any so commands a program to find last and first name from a string containing the full name two parts are separated by one or more blanks so these are just the initial declarations and inclusion standard inclusion of libraries etcetera let us look at the program first the data declarations I am declaring a name string ok name string 256 character elements what am I going to do this I am going to read the whole line how big can a line be ordinarily a line can be 80 characters long because on a screen you can type 80 characters but suppose I have prepared the list using a data entry operator whose line length was larger he put a new line character only at the end of that larger length in general it is a good practice to allocate larger number of character positions to hold a string which comes from an input line I have arbitrarily decided to put it as 256 I am declaring a character pointer star char ptr this can point to any character variable or any element of character array now I declare two arrays first name and last name I am I am saying 80 elements but please note that each one can hold only a string of 79 characters why because the last character of a string must be a null character as per the c string definition I have two simple variables n care obviously it stands for number of characters and blank pass which perhaps is used to indicate the position of a black we shall explain how exactly we use we use these variables here length f length l I I is obviously some kind of an index variable length f and length l although I have not explained by commands but you can guess that this is the length of the first name and this is the length of last name so once again name string name str is an array which can hold up to 255 characters and we shall use this to read the entire string from the input line care pointer is a character pointer we define two character arrays of 80 elements each to hold first name and second name each of which can be 79 characters long and we have some other variables which we shall use in the course of this program the program begins by asking me saying type a name and then instead of using c in I am using a function from the standard c library we shall soon be looking at scan f and print f gate s is of the same generic what gate s does is as I explained earlier it reads a line and assigns all characters of that line into consecutive elements of the array pointed to by whatever name you are given note that name string is an array so the first character on the input line will go to name string 0 second will go to name string 1 third will go to name string so on up to I I press end of line whenever I the input mechanism detects that end of line it chops it off and puts a backslash 0 in the next position in the array consequently I have a valid c string inside the array name str I use another function to find out how many characters have actually got for example, Nandlal, Blank, Sarada and I put a new line character I will have so many characters but if I have a larger name Venkatapatti something something then I will have larger number of characters whatever it is string length function str alien is capable of giving me the length you remember when we looked at character string we wrote a small program to calculate the length we can do it ourselves but see as inbuilt function so we use that string length name str will get me the length of the string as determined by the position of backslash 0 in that name string so whatever is the last character by that new line character I put that will be that will be the last position plus 1 and I will get the appropriate length I am putting that in Ncat I am calculating the length well if Nandlal, Sarada or Deepak Phatak are the strings then I do not want to keep on examining any extra I should examine only these to find out whether there is a blank or not what is the first part what is the second part I proceed ahead with this locate the first space remember what we are required to do is very simple let me let me just switch over to this paper for a moment this is how the character will character string will look inside inside the string so this will be the 0th element this will be the first element second element and so on this is the string name string the name string array contains this the length of the character string will be this much this is what will be written by the function string length what I want to do now is I want to examine these and find out the location for first blank because I know that before the first blank everything is first name after the blank may be more than one blank then I have second how do I locate this there are two ways one I can set up an iteration around name string starting with 0 examine 0th character first character second character third character etc till I find a blank however C has a very interesting function for this matching of characters and finding out whether there exists a character inside a given string so let us look at that we say here locate first space care pointer equal to care star mem chr name string comma blank comma nchr this is a blank character opening code blank closing code what does this function do mem chr it searches for a given character which is blank in this case inside a string which is given by array but it does not search all string it searches for only so many characters ordinarily I would have said does not matter such the whole string but there are occasions when I want to search only specified portions starting from the first point so that is why this variable is included nchr obviously is the length of the string so the entire non-lal blank sarda is included in this so in that entire string I invoke this function if what it actually does is it finds out if the blank exists if blank exists then it will point it will return a pointer to that blank position so wherever that position is return a point if the blank does not exist in this name it will return what is called a null pointer null pointer is a valid value for a pointer null is actually absolute 0 and absolute 0 does not point to anything although there is a memory location with address 0 it is not meant for us it is never meant for any program so c programming language specifically says that a null pointer does not point to anything consequently whenever it fails to search for a character because it does not find it it how will it indicate to you because it is always going to return a pointer only that is the nature of this function this function returns a pointer in the bracket writing care star this is called typecasting so whatever this fellow returns actually it may return an integer value it is typecast as care star as a point when I say care ptr is equal to this now my care ptr is pointing to a particular location inside that array address of that location which contains blank that is very quickly for a moment go back to this handwritten note and I will show you what I mean by this so here if you see this is zero this is one this is two three four five six a blank occurs at seventh place that means so actually the care ptr that we looked at that pointer will point to this this is the nice work that this simple function does for us so notice that we could also independently do it by setting up a iteration now we know that if the blank was found then the care pointer will have a non-null value so I say if care pointer is not null not equal to null if it is null then obviously there is no space if it is not null one blank found get first name notice how I am getting the first name care pointer points to seventh element 0 1 2 3 4 5 6 seventh element minus name string which is the array name itself array name points to the first element of the array always plus one seven minus let's say zero plus one okay so the blank position itself I calculate by doing this I I say found blank at blank position so and so length f is blank pause so I do all this I have identified a blank I have found out the position of that blank and now I want to copy only the first name notice how it is being done by another function strncpy what does strncpy does strcpy is a string copy function strncpy copies in number of characters from one string to another so from name string it will copy to first name both must be arrays of course and the copying will be from 0th element to 0th first to first etc how many characters length f what is length f length of the first name however determined length of the first name based on the value of the blank this is not the blank pause that I I got pointed to by this notice that I added one here so this computation you can verify by the way by writing down the array elements and checking what is the value returned etc etc this strncpy will actually copy the first name that means the entire string up to the first blank up to the first blank not including the first blank and and put it in the first name what is the length of that first name it is length f the length fth element must be backslash 0 none the law is my name not none law blank the blank pointer is pointed to by this so wherever there was blank I actually copied and replace it by backslash 0 making none law a valid string in the array first name otherwise if I said none law blank and left the array rest of the array to contain whatever then the array first name will not contain a valid c string remember I am constructing a string first name had nothing and when I construct a string it is mandatory for me after putting it the desired characters of the string inside that array I must put a backslash 0 so I am putting a backslash is no backslash 0 is 0 actually in fact null backslash 0 they are all 0 so I am assigning a value 0 when I do that my first name will actually contain the first name so what do I do I output some string first name is and how do I output individual characters for I equal to 0 I less than length f I plus plus I see out first name I so either element 0 is the element first element so consequently what will come out you know from the computer N A N D L A L these characters will come out at the end when I reach length f less than length f I will terminate this and push a new line so in all this Jamela all that I have done is taken the original string identified the position of a blank in that string notice that this part on the left hand side will be the first name transfer those many characters into an array called first name push the backslash 0 in that first name array to make that a legitimate string and printed it out sound simple let us look at the next part of the problem now I know I am currently positioning blank process positioning at the blank position in the original name string okay I had none of the blanks are it could have been none of the blank blanks are if somebody gives multiple blanks what up now I want to get the second name the first name ended when the first blank was found out but the second name may not begin immediately after the first blank because the possibility that somebody might have been multiple blanks so what I do having found on blank I keep looking at the next position of next of the character string that I have read and as long as they are blanks I simply keep omitting this is what is being done skip consecutive blanks if any so see what I am doing while name string blank pos equal equal blank blank pos plus plus very simple so I am nearly changing the blank pos value which is the index value by one every time I notice a blank so consequently when I come out of this iteration which is a high iteration okay I must by the way also check whether I have already exceeded why when could that happen that could happen if somebody gives me an input which says none law and nothing else so actually is cheating me he does not have a second name but I should be smart to say that if why inside this while loop as I am examining successive blanks if suddenly I reach n care which was the length of the original string then somebody has not given me a second name so I now say no last name and return one so if I reach this no last name otherwise when I come out of this loop blank pos will point to the last consecutive blank plus one so what do I do now I find and print last name here are some computations n care was the total length of string blank pos was the position of first non-blank character difference will give me length of last name I will again use copying n characters from one string to another the string from which I have to copy is not name string but name string plus blank pass please note this funny arrangement this is possible because as I told you array name is actually a pointer to the 0th element when I add a blank pass to it suppose blank was 7 then it will point to 7th element which is one more than blank and then the length elements I will transfer to last name which I will get here last name length l is equal to 0 and length l I have already calculated how much is the last name length similarly I will output last otherwise remember when we said that while loop I have returned one or whatever name has only one word return 0 please do execute this program let's see what happens these are successive execution results I type a name none large order it says found blank at 8 first name is none large last name is sorry let us continue type a name Deepak notice blank blank blank blank father found blank at 7 first name is Deepak all right but the last name it does not give us blank blank father it omits all the blanks remember that while loop let's take another example type a name Shreeder I am not type Shreeder Iyer which is the name of another colleague of mine I was just type Shreeder is no second my program correctly says name has only one word but if I execute again with this input notice that I am giving the name Kavi Arya for you admit is readable as Kavi Arya but for computer there is blank blank blank blank Kavi blank blank blank Arya now it says found blank at one that means the first position itself is blank so first name is null actually now it will omit consecutive blanks but where here first second third for these blacks will be omitted and it is now trying to find out the last name the last name is equal to the whole length including these blanks that is why funnily it says last name is Kavi blank blank blank Arya in short the program appears to work correctly but on some crucial input it shows me inadequacy of my algorithm so it types a name if I type this name it will say first name is nothing last name is Kavi Arya you might want to consider correcting that or modifying the program at your leisure this is not part of the assignment today the assignment is different sorry before the tea break I would like to interact with all the participants if they have any questions here there is a query from well lower institute we are going over to well lower good morning sir I am Kumar from VAT my question is can we make the local variables to exhibit the proper the properties of a mobile variables by passing them as reference variables because in the recent explanation you have given you have shown that by making the local variable receiving as a reference variable that change the value whatever we change in the column function will get reflected so it sounds like the local variable can be made back as a global variable you think it's true sir can I make like that thank you very much it's a nice question for my AV readers I would like to reiterate this question the question is because by passing by value I am almost making a variable have characteristics like a global variable so is that so by passing by sorry passing by reference do I make a normal local variable into a global variable the answer is actually no and the reason is as follows when I pass a parameter I am passing it to a particular function even if I pass a pointer the address of the corresponding parameter is passed and it is true that in that limited sense the variable which I have declared in the main program behaves like a global variable as far as the called function is concerned but imagine a large program in which there are 20 functions written a variable X or Y which is localized somewhere it may behave appear to behave like a global variable in the called function but in rest of the program it is not a global variable while we have not discussed the scope but if I declare variables with scope global or static we shall discuss this separately then those variables are supposed to be known everywhere in the entire program body by the way if I have global variables then I do not need to pass parameters because those global variables will be known inside every function the objective of function is different the objective of function is to do similar computations on different values or different variables or different direct consider the same thing that I mentioned to you that I have a short utility or short function I have written which is sort a given area or a matrix multiplication utility which will multiply two matrices and give me the reason if I have insisted on global variables then only a specific set of matrices will be multiplied but if I have multiple matrices once I want to multiply this two matrices next time I want to multiply other two matrices or in case of sorting I want to sort one area once second area another type third area another type that is the beauty of a function called with different parameters the function itself is written in terms of a single name but I am passing different pointers or different values to it coming back to your original question the global variables are separate breed they are truly global in the sense that the entire body of the program they are known the function called by reference might appear as if it is it is showing the science of the behavior of a global variable but that is not true passing by reference is exactly what it says passing by reference there is a function in which that function will operate on the original value pointed to for this function if somebody has caused that function from somewhere else then that function will operate on the other other so the objectives are different I hope this answers the question okay we have a query from dox Srinagar over to you dox Srinagar good morning sir I am Nisar from dox center Srinagar my question is why does KNF behave strangely when we input multiple string values one after the another using person test as compared to using get S and put S okay the question is why does KNF behave funnily when we put multiple consecutive strings as compared to when we put get S so I not only sympathize with you but I have been a victim of similar things I was thinking that since I am not a good expert in C programming that is why it is happening but if you also reported scan F behavior must indeed be funny let me simulate this behavior I request you to do one thing whatever funny behavior you have found please document it and send a mail I will consult some of my colleagues here and I will consolidate this answer because I propose to discuss scan F and print F tomorrow along with the file IO and therefore I we can we can discuss this but on my part I never really like scan F for handling string I always use get string or get C there is a query from Rajaram Bapu College over to you hello sir I am Varsha Talukri from Bhattu I want to ask you a question better null pointer points to any memory location or to you I know as I told you null value of a pointer is a very special value and it signifies that the pointer does not point to anything so as far as C programming language is concerned if a pointer ever gets a value null I repeat it does not point to anything meaningful so if at all I try to access the value pointed to by a pointer which has a null pointer then unpredictable results will occur so C language is very very clear on this null pointer does not point to anything as a matter of fact that is the reason why most functions like what we saw in care functions if they do not find something useful they return a null pointer indicating that there is there is nothing to be returned it has not found it so I repeat null pointer does not point to anything there is a query from NIT Durga poor okay thank you very much I will I will try to casual of a meaningful example a huge pointer and he is asking how do we explain to our students huge pointer and far pointer you are asking a person this question who hates pointers I personally believe that using pointers is a very bad way of writing programs unfortunately while writing programs in C or C plus occasionally the only decent way of solving a problem is to use pointers however from higher level programming languages pointers should be banned if you notice if you notice the pointers are not used in most other languages Java specifically bans you from using pointers you look at it this way as far as programmers are concerned what are they dealing with they are dealing with value they are dealing with values of arrays and variables later on as we shall see they will be dealing with later on they will be dealing with structures they are they will be dealing with records in five in short in my program I want to write instructions which will deal with values compute new values put values into some locations put values in some five what actual addresses the compiler is using to allocate memory to why should I be concerned with it it is a legacy which comes from 1970s and that legacy has still continued unfortunately by stipulating pointers to be explicitly a portion of my syllabus I am forcing my students to use pointers it is one thing to explain to them the meaning of pointers and explain to them some nice things which can be done easily in C programming language but to extend it to far pointer huge pointer infinite pointers whatever whatever whatever is a travesty of fate we are the more we do that the more we are moving away from programming concepts this is of course my opinion it is not shared by those hundreds of people who have written syllabus and write exam papers so I am the wrong man to ask this question however since we are discussing the subject and the subject must be completely discussed in all its dimension I will put up a slide on far pointer and huge pointer I have put a portion for miscellaneous discussion in coming days I propose to compile all the answers to various questions and put them together so thank you very much for asking this question let me go over to Jaipur engineering college cook us so the question raised by Jaipur engineering college is that how do we use pointers in Java or why pointers are not permitted in Java unfortunately this is not the right place to answer that question because that question should be answered in a in a when a subject is discussed which is object oriented programming or Java programming but I will answer it which is nothing but the extension of what I just told you Java programming language understood it was it please understand that Java was defined much after C and C plus plus as a matter of fact the designers of Java programming language saw not only the use of pointers in C C plus plus but the chaos that it could cause particularly in large software which is thousands of lines long and where people are not very careful with pointers where pointers get computed and assigned null values and when people still try to access the location pointed to by them which I just explained null pointer then point anywhere and this causes a huge chaos unpredictable errors in the programs and so on so they reason much like what I was reasoning that for a programmer how does it matter where my values are stored in array of my arrays and variables and structure let the compiler and the operating system handle it as far as I am concerned I am to deal with those values Java probably takes this philosophical position and therefore discourages you from using pointers internally it does use pointers but they are not visible to programmers so in that sense Java is actually a cleaner language there is a question from IMCC Pune I am going over to IMCC Pune his question would fall under what we call the advanced category what he is observing is that some system calls are already present in the operating system by the way the terminology is slightly wrong system calls are not present but system functions are present so operating system has three written functions which performs certain things which we would like to call for example finding out the time for which a process runs or getting a process ID etc these would be done through system calls so you are very right ordinarily I can actually invoke a system called directly the question is is more is slightly deeper than that how can I get pointers to those functions so that I can use them we have not actually discussed function pointers and therefore I cannot answer that question here I will try and put up a slide on the function pointers however I would very strongly suggest that in the first course in programming please do not spend time in discussing function pointers it is adequate for people to be able to make system calls which they can do by actual mechanisms which is provided as part of the C programming language I will give examples of how to make function calls from C but function pointers or pointers to those system functions in my opinion is is not the right way or is not the right material for a first course in programming thank you so much it is 11 o'clock thank you over and out