Pointers

715 views
629 views

Published on

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
715
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
31
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Pointers

  1. 1. Page 1 of 24 PointersImportant Points before you proceed :  A variable declared in a C++ program occupies some memory space.  Every variable is given this memory space randomly.  Each of these memory spaces given to variables, could be identified by its unique Hexadecimal address, like : 0xAFFC for eg.  Every variable occupies different length of memory space depending on its data-type (like int, char, float so on…)  The value assigned to a variable is being stored at the address of the memory location being assigned to it.  The memory location being assigned to a variable remains reserved till the program scope is alive.Try to answer (compulsory before you move to later part):Q: Declare an integer variable and store a value equal to 5 in it.Q: Declare two variables a and b initialize them with two values and try to swap their values.Q: Try to execute the following codes and observe the result : #include<iostream.h> #include<conio.h> main( ) { char points[ ] = “We are KVians” while(points[i] != ‘/0’) { cout<<points[i]<< “n”; i++; } }Pointer Overview and Need :We declare simple variables in C++ by the statements like : int a ; // an un-initialized integer variable float b ; // an un-initialized float variable char MyVote = ‘Y’ ; // a initialized character variable Prepared By Sumit Kumar Gupta, PGT Computer Science
  2. 2. Page 2 of 24All of the above variables that we have declared are termed as simpleprogramming variables (You learned about them in Class XI) .The concept of pointer is not new in C++ , it has been there in right from thegeneration of Language – C. Language C is considered as one of the mostefficient middle level programming language, because of its ability to write codesfor hardware devices, like CPU , Disk Drives, Keyboards etc. One of the facility inC which provided it these capabilities was the presence of Pointers with it.Following are some of the application area domains where a Pointer conceptcould be applied: a) Writing Device Drivers (a middle ware). b) Communicating with Network and I/O devices. c) Implementing complex Data Structures Like Stack ,Link – List , Queue etc.(which you will read after this chapter) d) Implementing many complex algorithms faster.Pointer Definition :A pointer is a variable which stores the memory address of anothervariable of same data type.Let us try to explore this definition with a particular example : int a = 32 ; // a simple variable being initialized with a // value equal to 32When the above line is being executed by the compiler, it will allocate thevariable a with a random hexadecimal address say : 0x8fbffff4. This memoryaddress will remain attached with the variable a till the variable is present in theprogram scope. Try to Do : Copy the above hexadecimal memory addresses and convert it using calculator to its decimal form. Write the decimal equivalent in your notebook.The above scenario could be represented pictorially as : a variable a 32 Prepared By Sumit Kumar Gupta, PGT Computer Science
  3. 3. Page 3 of 24 a memory space of 2 bytes with a value equal to 32 0x8fbffff4 Hexadecimal address being allocated to variable a. For sake of simplicity from now onwards we would take decimal values asvariable addresses instead of taking hexadecimal addresses.We are observing that the addresses allocated to simple variables are themselvesa type of values ( i,e hexadecimal values). So a question arises that can’taddress values be stored again in some variables? If yes, then what would be thedata type of those variables? Whether those variables would be like simplevariables or different from it? What would be the size of those variables?Let us try to sort out the answers of all of the above questions.Since a variable which is storing an address of another variable, must be aspecial one, so in C++ these variables are treated specially and are declaredusing special syntaxes.Pointer Declaration:A pointer declaration is similar to the declaration of a simple programmingvariable except that it is declared with a (*) asterisk symbol. The syntax is asfollows : <data type> * <Pointer variable_name>For eg. : int * iptr ; // an integer pointer variable char * cptr ; // a character pointer variable float * fptr ; // a float pointer variable Note : The pointer variable name obeys all the rules and regulations which a normal variable naming follows. Pointer also have some data types.Pointer Initialization:We know that a simple variable is initialized with a value using assignmentoperator ( = ) like : int a = 20 ; // a simple variable initialized by a value equal to 20 Prepared By Sumit Kumar Gupta, PGT Computer Science
  4. 4. Page 4 of 24Likewise whenever we declare a pointer variable we must initialize it with aparticular value using the same assignment operator (=). But as we know fromearlier definition of pointers that a pointer variable only holds an address ofanother variable, so the value assigned to a pointer must be an address ofanother simple variable of same data type.Extracting Address of a simple variable :One of the biggest question arises that : How to extract or find the address of asimple variable so that it could be assigned to a pointer variable. For This wehave a special operator for this purpose i,e. ( & ) ampersand ( read it asaddress of operator ). This is a unary operator whose sole motive is to returnthe address of the variable which is present in the R.H.S of it.Consider the following code : int a = 20 ; // Line No. 1 int * ptr = &a; // Line No. 2The Line No. 1 of the above code snippet creates an ordinary variable a havingan integer value equal to 20.The Line No. 2 of the above code snippet creates a Pointer variable ptr having avalue assigned to it. We observe that the value assigned to it is the “address ofa” ( i,e. &a). So from the above code it is inferred that a pointer variable (ptr)must be initialized with address of a simple variable (a). int a an integer variable a 20 the value 20 0x8fbffff4 &a ( address of a ) int *ptr an integer pointer variable 0x8fbffff4 &a ( address of a) as value Very Imp. Note : Try to initialize a pointer variable with an address whenever you create one such. If you are not initializing it will point no where or to some garbage address , that would result Prepared By Sumit Kumar Gupta, PGT Computer Science into unpredictable program results. We can initialize a pointer variable with a NULL (‘/0’) value.
  5. 5. Page 5 of 24Try to Answer these (Lab Work) : a. Create a float pointer variable fptr and a Simple integer variable var. Try to assign the address of var into fptr. Execute and infer the result. b. The addresses of any variable is a hexadecimal value ( or an unsigned integer value ), then why do we need different data types for declaring pointers. [ Hint : Declare two or more pointer variables with different data types and try to find their individual memory size by using sizeof ( ) operator. c. Execute the following code (include the required header files of your own) and observe the output : main( ) { int a = 35 ; cout<< a; int *p = &a ; cout<< p; getch(); } d. A pointer variable is also a variable so it will also occupy memory space. Since it occupies a memory space it must be also having some fixed memory address. If this memory address has to be stored then what type of variables we would need? Whether it would be a normal variable, a pointer variable or something else? Explain. The de-reference operator ( * ) : One of the most confusing operator in pointer notation is the use of the operator ( * ) asterisk. The meaning of the symbol (*) changes at following different situations : i) when we declare a pointer variable ii) when we try to read a value present at the address which is held by a pointer variable. Let us understand the above two scenarios : Prepared By Sumit Kumar Gupta, PGT Computer Science
  6. 6. Page 6 of 24i) When we declare the pointer variable we are in habit to write : int * p ; [ here the * only indicates that p is a pointer variable]ii) When we read a value from an address: int a = 20 ; int * p = &a; The symbol * is used to declare as well as assign an address to a pointer | variable p cout<< *p Trying to print the value which is stored at the address being held by pointer p ( here in this case p is holding the address of variable a , so it will print the value stored at that address , ie. The value of a itself which is 20). int a int *p (declaring pointer using * ) 20 0x8fbffff4 address of a ( &a or p 0x8fbffff4 itself) value at p (a or *p ) Note : * ( value at ) operator is a unary operator which is always used with an address present at R.H.S of it. If we place a value at the R.H.S of a pointer variable, instead of an address then it would cause an error “Invalid Indirection” . For. Eg : if int a = 30 then cout<< *a ; will cause error. Similarly if we print cout<<*5 , it would cause error. Execute the following and see which of the two lines are giving same output: main( ) Prepared By Sumit Kumar Gupta, PGT Computer Science
  7. 7. Page 7 of 24 { int a , *ptr ; a = 30 ; ptr = &a; cout<<a << “n”; cout<<&a << “n”; cout<<*ptr<<”n”; cout<<ptr<<”n”; getch( ); }Using New and Delete Operator:Execute the following and analyze the run time error : main () { int a[4]; // fixed sized array for(int i = 0 ; i <= 5 ; i++) { cout<< “nInput”; cin>>a[i]; cout<< “n a[i]”; } getch(); }When you execute this code you will find that the code will take 6 inputs andthen it will terminate abnormally by either displaying message “Programterminated abnormmaly” or “Your CPU encountered illegal instruction”.Can you say why it did happen?You see this happened because we have declared a fixed size array in linenumber 1 by writing int a[4]. This fixed size array is being allocated in 4 * 2 = 8bytes of contiguous memory location. While our for loop statement in theprogram is iterating for 6 times. So after reading a 4 inputs the CPU step on toread and write that memory location which is not the part of the static arraya[4]. So it causes a Run time error.This is one of the problems we face with Static arrays having fixed size; moreproblems may arise due to its static nature (try to find out some more errors anddrawbacks). So we are in desperate need of an array variable whose size could Prepared By Sumit Kumar Gupta, PGT Computer Science
  8. 8. Page 8 of 24be well defined during the run time of the program, not during the design timeitself, as is done in the case of the example given above.C++ provides us with a NEW operator to create fixed size array with a sizedefined during run time. This whole block is treated to be a static block ofmemory but created in a more dynamic way, asking the size of the array to beinputted from the user.Let’s understand the concept by running the following code snippet: main() { int *MyArray; // Line 1 : int size ; cout<< “Define the size of the array you want to create”; cin>> size; // Line 4 MyArray = new int[size]; // Line 5 : initializing pointer MyArray with an address. for(int i = 0 ; i <= size-1 ; i++) { cout<<”Input a value n”; cin>> MyArray[i]; } for( i = 0 ; i <= size -1 ; i++) { cout<< MyArray[i] << “n”; } getch(); } Observe the Line 1 , 4 , and 5 of the above program. In Line 1 we have declared a Pointer variable which will act as a address holder. In Line 4 we ask user to input desired number of array members (i,e : size ). Finally in Line 5 we acquire the required memory space at runtime using the new operator by statement: MyArray = new int [size]; Can be supplied during design time or during the run-time.Where, MyArray = a pointer which holds the address of the first member of the array created at R.H.S using new operator. Prepared By Sumit Kumar Gupta, PGT Computer Science
  9. 9. Page 9 of 24 new = Keyword to allocate memory chunks during run-time. int = required data-type of the array – member. This data-type can be also float , char , void etc. size = the required amount of memory chunk, defined by the user at design time or run –timeThe Delete Operator :The memory chunk allocated by new operator during run-time, assigned to apointer remains reserved till you restart your machine. That means that if theabove explained program is executed for 10 times then it will reserve10 * size * 2 bytes in memory, and all these bytes would be reserved till yourestart your machine. This reserved memory can’t be used by any otherprogram, till we restart machine. Hence in some situations the scarcity ofmemory occurs. This scarcity is also termed as Memory Leakage. To avoid thememory leakage problem the programmer tries to release the reserved memoryspace just when he feels that no more the reservation is required. This de-allocation process could be done using delete operator.Consider The statement : int * MyArray = new int [size];In the above step since the pointer MyArray holds the base address of thememory chunk thrown to it by new operator in the R.H.S. So if somehow we aresuccessful in making this pointer to forget this base address, we are done withour job of releasing the reserved memory space. This is exactly being done bythe delete operator by using the following statement : delete MyArray ; // delete the reference held by the pointer MyArray.Pointers and Arrays:const Pointers :We can create a ordinary const variable by using following syntax : const <data-type> <var_name> = <value>; Eg. const int MyVar = 2;One of the most important characteristics of a const variable is that, once theyhave been assigned with some values, that value could not be changed at anypoint of time throughout the whole program. Prepared By Sumit Kumar Gupta, PGT Computer Science
  10. 10. Page 10 of 24For example in the above statement MyVar is a const variable and its value couldbe reinitialized or changed again i,e we can’t write following statement after wehave declared MyVar as const : MyVar = 23; // InvalidOr MyVar ++ ; // InvalidLikewise we can have out pointer variables also as const pointer variables byusing the same syntax as above with a slight modification, such as : const int * MyConstPointer = &<some variable>;More precisely : int a = 20 , b = 30 ; const int * MyConstPointer = &a;After we have declared a const pointer, we can’t change its address any how, atany point of time in a program. So writing the following codes would causeerrors: int a = 20 , b = 30 ; const int * MyConstPointer = &a; MyCostPointer = &b; // Error ! can’t assign a second value to a const pointer since it has already been initialized with the value i,e address of variable a.Pointer Arithmetic :Lab Activity :Part a) Execute the following code and note the two output lines obtained. main( ) { clrscr(); int a = 20 ; int * p = &a; cout<< p ; p++; cout<< p; getch( ); } Prepared By Sumit Kumar Gupta, PGT Computer Science
  11. 11. Page 11 of 24Part b) Execute the following code and note the two output lines obtained. main( ) { clrscr(); float a = 20 ; float * p = &a; cout<< p ; p++; cout<< p; getch( ); }Part c) Change the Hexadecimal value obtained in parts a) and b) of the activity into its corresponding decimal values (taking help of the system scientific calculator).Part d) Subtract the first output from the second output in each case i,e part a) and part b). Observe the two results (decimal values) obtained. Is it coming 2 and 4? Why? What idea you get from it?As we can add or subtract integers from a normal variable, likewise we can alsoadd and subtract integers from pointer variables. So all of the followingstatements are very correct: int a = 80 , b = 90 ; int * MyPointer = &a , * YourPointer = &b; MyPointer = MyPointer + 1; YourPointer = YourPointer – 2 ; MyPointer += 5; - - YourPointer ;What happens when we increment / decrement a pointer variable by acertain value ? Note : Never try to apply multiplication, division or modular division operator on Pointers. Pointer arithmetic does not allow these operations. So the statements like: int var = 30 ; int *ptr = &var ; ptr /= 2 ; ptr % = 4 are invalid operations.What would be the output of the following code snippet and why? Prepared By Sumit Kumar Gupta, PGT Computer Science
  12. 12. Page 12 of 24 main ( ) { const int * ptr ; int a = 80 ; ptr = &a ; a += 3; cout<< a; ptr++; cout<<ptr; }Creating Arrays with pointer:We have already seen that a pointer can hold the base address returned by newoperator while allocating a required chunk of memory space. For eg : const int * ptr = new int[5];The above statement will allocate 5 * 2 = 10 bytes contiguously one afteranother at adjacent locations (memory addresses). The first address out of all,these set of addresses being assigned to pointer ptr. The picture we obtain canbe viewed as :memory 8fc4fff4 8fc4fff6 8fc4fff8 8fc4fffa 8fc4fffcaddresses ptrIf you observe the whole scenario you will find that directly or indirectly we aregetting an array containing 5 members, each of these members having a integervalues (int data-type). The base addresses being assigned to the pointer variableptr itself.Now we are free to apply the pointer arithmetic to the base pointer ptr to readand write other locations as well.The first location is ptr can be referred as (ptr + 0) ie. 8fc4fff4.The second location can be referred as ( ptr + 1) ie. 8fc4fff6The third location can be referred as ( ptr + 2) ie. 8fc4fff8The fourth location can be referred as ( ptr + 3) ie. 8fc4fffaThe fourth location can be referred as ( ptr + 4) ie. 8fc4fffc Prepared By Sumit Kumar Gupta, PGT Computer Science
  13. 13. Page 13 of 24Similarly to read and write value at these locations we can readily use (*)operator i,e.*ptr i.e. *(ptr +0) reads/writes value at the address held by ptr i.e. at 8fc4fff4.*(ptr + 1)  reads / writes value at the address held by ptr+1 i,e. at 8fc4fff6.*(ptr + 2)  reads / writes value at the address held by ptr+2 i,e. at 8fc4fff8.*(ptr + 3)  reads / writes value at the address held by ptr + 3 i,e. at 8fc4fffa.*(ptr + 4)  reads / writes value at the address held by ptr i,e. at 8fc4fffc.Now let’s think the whole process in reverse order. Thinking in reverse manneryou find that we have ultimately created a 1-Dimensional Array having 5elements in it.Let us proof this by comparing the following two programs :main ( ) main( ){ { int arr[5] ; int *ptr = new int[5]; for(int i = 0 ; i<=4 ; i++) for(int i = 0 ; i <= 4 ; i++) { { cout<< “Input ”; cout<< “Input”; cin>>arr[i]; cin>> *(arr + i) ; } }} }Both of the above versions of the programs are equivalent. Thus we can inferthat the name of base pointer (ptr) in the second version is acting same as thename of the array (arr) itself present in the second version. Note : The name of any array declared in any C++ program, is a pointer to the address of the first element of that array.The above two versions can be used in compliment of each other, as and whenrequired. They can also be used in mixed form. So the following expressions areequivalent : arr[i] Ξ *(arr +i)So , following mixed expressions can be used while writing codes using arrays : main( ) { int MyArray[5] ; Prepared By Sumit Kumar Gupta, PGT Computer Science
  14. 14. Page 14 of 24 //Inputting array elements for(int i = 0 ; i <= 4 ;i++) { cout<< “Input Values : ”; cin>> MyArray[i]; // Using array notation } // Showing array elements for( i = 0 ; i<= 4 ; i++) { cout<< *(ptr + i) ; // Using Pointer notation } }Lab Activity (proceed sequentially) :Part a ) : Execute the following code and note down the error if obtained otherwise note down the output main( ) { clrscr(); int arr[5] = {12 , 14 , 16 , 18} ; for(int i = 0 ; i <= 4 ; i++) { cout<< arr[i]; arr++; } getch( ); } // end of main( )Part b) : Execute the following code and note down the error if obtained otherwise note the output main( ) { clrscr( ); int *arr = new int[5]; for(int i = 0 ; i <= 4 ; i++) { cout<< “Enter a value :” ; Prepared By Sumit Kumar Gupta, PGT Computer Science
  15. 15. Page 15 of 24 cin>> *(arr + i) ; } for(i = 0 ; i <= 4 ; i++) { cout<< *arr; arr++; } getch(); }Part c) : What have you observed in Part a) and Part b) ? What inferences you draw from there outcomes. Note down all the inferences you approached.Part d) : Now execute the following code and note down the error or output whatever you get: main( ) { clrscr( ); const int *arr = new int[5]; for(int i = 0 ; i <= 4 ; i++) { cout<< “Enter a value :” ; cin>> *(arr + i) ; } for(i = 0 ; i <= 4 ; i++) { cout<< *arr; arr++; } getch(); }Part e) : Compare the result of Part a) and Part e). Write the inferences that you have drawn from this comparison in your notebook and show it to your teacher. By performing the activity given above you would find that all arrays declared in C++ are nothing but a const pointer having the address of the first element of the same array. Prepared By Sumit Kumar Gupta, PGT Computer Science
  16. 16. Page 16 of 24Pointer with different operators :Pointer with Assignment operator :We know that we can assign value of a simple variable into another variable byusing assignment operator ( = ) for e.g. int a = 90 , b = 80 ; b=a; The value of b is being replaced by the value of a i.e. 90Similarly we can use assignment operator ( = ) between two pointer variables.So the following code snippet is very correct: int x = 45 , y = 78 ; int * a = &x , *b = &y; a=b; // assigning pointers to each otherWhen we write pointer a = b then the address which is being stored in b i,e aHexadecimal value , gets copied into pointer a removing any of its previouscontents (address).Pointer with comparison operator ( ==)Just like we use comparison operator (==) between two simple variables, we canalso use it between two pointer variables.What would be the output of the following code : main ( ) { int a = 30 , b = 30 ; if ( a == b) cout<< “I Liked this study material”; else cout<< “Who has made it yaar!!”; }Yes, you are absolutely right the output would be “I Liked this study material”,because the conditional expression a == b is evaluated to be true. Prepared By Sumit Kumar Gupta, PGT Computer Science
  17. 17. Page 17 of 24Now try to predict the output of the following code: main( ) { int a = 30 , b = 30 ; int *p = &a ; int *q = &b ; if ( p == q) cout << “Kamal, Are you joking !”; else cout<< “Pointer is so easy following this study material”; }If you are not able to find the answer yourself, execute the code and discuss withyour teacher. Note : Similarly we can also use != between two pointer variables. Sometimes we also compare a pointer variable with NULL or ‘0’ to check whether it is pointing No where.Pointers and Strings:We already know that a string is not just a 1-dimensional array of characters butit is 1 – dimensional array of characters which is terminated by a Null (‘0’)character. This can be well defined in terms of following diagram : char MyName [30] = “Kamal”; ‘K’ ‘a’ ‘m’ ‘a’ ‘l’ ‘0’Also we have gathered knowledge that the name of a 1-dimensional array isitself a pointer to the first member of that array. So the above diagram can bemore clearly represented as: ‘K’ ‘a’ ‘m’ ‘a’ ‘l’ ‘0’ Memory addresses 8fc4fff4 8fc4fff5 8fc4fff6 8fc4fff7 8fc4fff8 8fc4fff9 * MyName (name of the string) Prepared By Sumit Kumar Gupta, PGT Computer Science
  18. 18. Page 18 of 24So from above explanation we conclude that the name of a String variableis also acting as a pointer (pointing to the memory address of its firstcharacter).If we try to print the name of the String variable with a cout statement thenit will print the address of first character in the string.e.g. : the statement cout<<MyName ; will print 8fc4fff4 (or some otheraddress) Q. Now keeping the above figure in mind fill in the following blanks : a) MyName + 2 = ____________ b) *(MyName +1) = ____________ c) *(MyName + strlen(MyName) ) = _____________ Check this out with your teacher. Conclusions : i) We know that a string is terminated by a null character. ii) A string name is a pointer to the first character i,e name of the string is holding the base address of the string. By analyzing i) and ii) above we find that now there is no need to declare a string like char str[30]; (as we have done in class XI). This can be more dynamically declared as char *str (The benefit here is that we don’t have to fix the size). Only declaring a character pointer is sufficient to hold an entire string, since the end point of the string will be automatically marked by NULL (‘0’) character, during run time. Hence: char str[30] Ξ char * str = new char[30]; or more dynamically as , char *str; Whatever string you assign to this it will accommodate, since the only need is to mark the beginning and end memory locations of the string. Prepared By Sumit Kumar Gupta, PGT Computer Science
  19. 19. Page 19 of 24Try to find the error or output:#include<string.h>main( ){ char * MyName = “Kamal Kant Gupta”; int i = 0; while( I <= strlen(MyName) -1 ) { cout<< *(MyName + i)<<”nt”; } getch( );}Q: Observe the following two codes and then put your views about one of them which you feel is better implementation than the other. (Both the implementations solves a same problem). Give reasons. main( ) main( ) { { char *book = “The Alchemist”; char *book = “The Alchemist”; while( *book != ‘0’) int i = 0 ; { while( *(book+i) != ‘0’) cout<< *book ; { book++; cout<< *(book+i) ; } i++; } } }Pointer to a Pointer:So far we have understood that a pointer is also a special variable, which ishaving a special role to play. One question that might strike in your head that if apointer is a variable it must also have some memory allocation with a specificmemory address (Hexadecimal address). Yes you are perfectly right. Pointers dohave their own addresses just like a simple variable. Prepared By Sumit Kumar Gupta, PGT Computer Science
  20. 20. Page 20 of 24Now a million dollar question arises that if pointers do have their own memoryaddresses, then their might be some variable which must be having ability tostore memory address of a pointer.Yes there are special variables which are intended to store the memoryaddresses of other pointer variables. These special variables are called pointerto a pointer or more precisely Double Pointers. The whole scenario could beexplained by following diagram: int a Ordinary Variable value of a 56 address of a 8fc4fff2 int * aa Pointer variable storing address of a 8fc4fff2 value of aa address of pointer aa 9acfff4 int ** aaa Pointer to a pointer variable 9acfff4Declaring Double Pointer variable:A double pointer variable can be declared in the same way as a normal pointervariable except that its declaration will involve two * (asterisks). For e.g. int a = 32 ; //simple variable having value 32 int * aa = &a; // normal pointer variable storing the address of a int ** aaa = &aa ; // double pointer storing the address of aa (which is itself a pointer)=Note : A double pointer is always being assigned the address of another pointer variable , or the value of another double pointer variable. If we try to assign the a value of simple pointer variable into a Double pointer it will cause error. E.g. : int a = 90 , b = 46 ; int *p = &a ; int * q = &b; Prepared By Sumit Kumar Gupta, PGT Computer Science int ** r = p; // Invalid assignment can’t assign simple pointer to a double pointer int **s = &p; int **f = s // Correct can assign double pointer to another double pointer.
  21. 21. Page 21 of 24Array of Pointers :In class you have implemented 2-D arrays as follows : int TwoDArray[3][3]; // a 2 D integer array of order 3 x 3 char CityName[ ][ ] = { “Delhi” , // five cities array “Kolkata”, // array of strings “Mumbai”, “Chennai” };The above example is implemented in terms of 2D character dimensional array.If you observe the 2-D character Array CityName more closely, then you will findthat it is nothing but a 1- D Array of String. Now since we know that a string canbe held by a single character pointer, hence to hold five city names we must besupplied with 5 character pointers. More precisely we must be having a 1-D arrayof pointers to get hold 5 different city names.Following figure will clear the picture : *str 0x4cff ‘i’ ‘D’ ‘e’ ‘l’ ‘h’ ‘0’ f2 0x4cfff2 *(str +1) 0x4cff f9 ‘K’ ‘o’ ‘l’ ‘k’ ‘a’ ‘t’ ‘a’ ‘0’ *(str +2) : 0x4cfff9 : *(str + 3) : :So the above implementation is based on the concept of Array of Pointers.An Array of string being an array of pointers has all its elements as address ofsome or the other characters. Now if we want to hold this whole array of stringby using only a single pointer can we do it. Prepared By Sumit Kumar Gupta, PGT Computer Science
  22. 22. Page 22 of 24Yes of course this can be done, just like you have captured the address of firstcharacter of a string into a char pointer, to grab the whole string, you can alsouse a double pointer to capture the address of first pointer variable of that Arrayof pointers.So to hold an Array of strings one can use a double pointer using following codesnippet: char CityName = { “Delhi”, “Kolkata”, “Mumbai”, “Chennai” }; or char ** CityName = { “Delhi”, “Kolkata”, “Mumbai”, “Chennai” };Exercise : Try to write a program which will read and write array of strings from user using the abovedouble pointer notation.Functions and Pointers :Pointers could be passed to functions as parameters just like we pass ordinaryvariables as parameters to the functions:Let’s understand how to pass pointers to a function by an example code: main( ) { int x = 70 ; cout<< x; IncreaseByTen( &x ); // calling the function IncreaseByTen passing // address of x cout<< x; } Prepared By Sumit Kumar Gupta, PGT Computer Science
  23. 23. Page 23 of 24 //function IncreaseByTen void IncreaseByTen(int *ptr ) { *ptr += 10; } Predict the output of the above code.The output of the above code snippet would be 70 and 80. This is becausewe have called the function IncreaseByTen( ) by passing the address of thevariable x as an actual parameter. This address is being copied into the formal parameter ptr of the function, which is a pointer variable. Since this variable holds the address of the x so any changes made at this address ( by statement : *ptr+=10 ) would made changes on the value stored at that address i.e. on the value of x.Similarly we can have more than one pointer variables as formal parameters to afunction separated by comma.Pointer and Structures:A pointer variable can also hold the address of a structure variable like it holdsthe address of an ordinary variable. Observe the following structure definition: struct Point { XCoord ; YCoord ; } P1 , P2 ; // P1 and P2 are structure variable. Now if you want to point a pointer to these two variables P1 and P2, then we have to declare the pointer variables like : Point *f = &P1; Point *l = &P2;One big question arises that how can we access the data members of a structurevariable using these pointer variables? Prepared By Sumit Kumar Gupta, PGT Computer Science
  24. 24. Page 24 of 24For this we make use of direction operator (). For example if we want to printthe value of the X- Coordinate and Y-Coordinate of structure variable P1 makinguse of its pointer f then we must write the statement as : cout<< f  XCoord << f  YCoord ; Remember : You access the data members of a structure variable using structure variable by using component operator ( . ) i.e. to print XCoord and YCoord of P1 you were writing : cout<< P1.XCoord << P2.XCoord ; Whereas if we try to access the data members of a structure variable using pointer to that structure variable then we make use of the direction operator  cout << P1XCoord << P1YCoord; Note : To the R.H.S of a Structure variable there must be a Component operator ( . ) to access its data member. To the R.H.S of a Structure Pointer variable there must be a direction operator (  ) to access its data member.Self Referential Structures :Consider the following Structure definition : struct Term { int coefficient ; int exponent ; Term *nextTerm ; };The above structure definition is a type of Self –Referential Structure , as wecan see that their exist a data member * nextTerm which is a pointer variable.The important point to be noticed that it is a structure type pointer variablewhich will store the address of the Next term of a Polynomial. Prepared By Sumit Kumar Gupta, PGT Computer Science

×