Pointers

24
Page 1 of 24 Prepared By Sumit Kumar Gupta, PGT Computer Science Pointers Important 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

description

This for the students of computer science and for those who want to learn about the concepts

Transcript of Pointers

Page 1: Pointers

Page 1 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Pointers Important 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

Page 2: Pointers

Page 2 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

All of the above variables that we have declared are termed as simple programming variables (You learned about them in Class XI) . The concept of pointer is not new in C++ , it has been there in right from the generation of Language – C. Language C is considered as one of the most efficient middle level programming language, because of its ability to write codes for hardware devices, like CPU , Disk Drives, Keyboards etc. One of the facility in C which provided it these capabilities was the presence of Pointers with it. Following are some of the application area domains where a Pointer concept could 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 another variable 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 32 When the above line is being executed by the compiler, it will allocate the variable a with a random hexadecimal address say : 0x8fbffff4. This memory address will remain attached with the variable a till the variable is present in the program scope. The above scenario could be represented pictorially as :

a variable a

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.

32

Page 3: Pointers

Page 3 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

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 as variable addresses instead of taking hexadecimal addresses. We are observing that the addresses allocated to simple variables are themselves a type of values ( i,e hexadecimal values). So a question arises that can’t address values be stored again in some variables? If yes, then what would be the data type of those variables? Whether those variables would be like simple variables 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 a special one, so in C++ these variables are treated specially and are declared using special syntaxes. Pointer Declaration: A pointer declaration is similar to the declaration of a simple programming variable except that it is declared with a (*) asterisk symbol. The syntax is as follows : For eg. : int * iptr ; // an integer pointer variable char * cptr ; // a character pointer variable float * fptr ; // a float pointer variable Pointer Initialization: We know that a simple variable is initialized with a value using assignment operator ( = ) like : int a = 20 ; // a simple variable initialized by a value equal to 20

<data type> * <Pointer variable_name>

Note : The pointer variable name obeys all the rules and regulations which a normal variable naming follows. Pointer also have some data types.

Page 4: Pointers

Page 4 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Likewise whenever we declare a pointer variable we must initialize it with a particular value using the same assignment operator (=). But as we know from earlier definition of pointers that a pointer variable only holds an address of another variable, so the value assigned to a pointer must be an address of another 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 a simple variable so that it could be assigned to a pointer variable. For This we have a special operator for this purpose i,e. ( & ) ampersand ( read it as address of operator ). This is a unary operator whose sole motive is to return the 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. 2 The Line No. 1 of the above code snippet creates an ordinary variable a having an integer value equal to 20. The Line No. 2 of the above code snippet creates a Pointer variable ptr having a value assigned to it. We observe that the value assigned to it is the “address of a” ( 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 the value 20 0x8fbffff4 &a ( address of a )

int *ptr an integer pointer variable

&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 into unpredictable program results. We can initialize a pointer variable with a NULL (‘/0’) value.

20

0x8fbffff4

Page 5: Pointers

Page 5 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Try 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 :

Page 6: Pointers

Page 6 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

i) 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 * ) address of a ( &a or p 0x8fbffff4 itself) value at p (a or *p ) Execute the following and see which of the two lines are giving same output: main( )

20

0x8fbffff4

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.

Page 7: Pointers

Page 7 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

{ 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 and then it will terminate abnormally by either displaying message “Program terminated 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 line number 1 by writing int a[4]. This fixed size array is being allocated in 4 * 2 = 8 bytes of contiguous memory location. While our for loop statement in the program is iterating for 6 times. So after reading a 4 inputs the CPU step on to read and write that memory location which is not the part of the static array a[4]. So it causes a Run time error. This is one of the problems we face with Static arrays having fixed size; more problems may arise due to its static nature (try to find out some more errors and drawbacks). So we are in desperate need of an array variable whose size could

Page 8: Pointers

Page 8 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

be well defined during the run time of the program, not during the design time itself, 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 size defined during run time. This whole block is treated to be a static block of memory but created in a more dynamic way, asking the size of the array to be inputted 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.

Page 9: Pointers

Page 9 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

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 –time The Delete Operator : The memory chunk allocated by new operator during run-time, assigned to a pointer remains reserved till you restart your machine. That means that if the above explained program is executed for 10 times then it will reserve 10 * size * 2 bytes in memory, and all these bytes would be reserved till you restart your machine. This reserved memory can’t be used by any other program, till we restart machine. Hence in some situations the scarcity of memory occurs. This scarcity is also termed as Memory Leakage. To avoid the memory leakage problem the programmer tries to release the reserved memory space 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 the memory chunk thrown to it by new operator in the R.H.S. So if somehow we are successful in making this pointer to forget this base address, we are done with our job of releasing the reserved memory space. This is exactly being done by the 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 they have been assigned with some values, that value could not be changed at any point of time throughout the whole program.

Page 10: Pointers

Page 10 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

For example in the above statement MyVar is a const variable and its value could be reinitialized or changed again i,e we can’t write following statement after we have declared MyVar as const : MyVar = 23; // Invalid Or MyVar ++ ; // Invalid Likewise we can have out pointer variables also as const pointer variables by using 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, at any point of time in a program. So writing the following codes would cause errors: 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( ); }

Page 11: Pointers

Page 11 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Part 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 also add and subtract integers from pointer variables. So all of the following statements 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 a certain value ? What would be the output of the following code snippet and why?

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.

Page 12: Pointers

Page 12 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

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 new operator 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 after another at adjacent locations (memory addresses). The first address out of all, these set of addresses being assigned to pointer ptr. The picture we obtain can be viewed as :

memory 8fc4fff4 8fc4fff6 8fc4fff8 8fc4fffa 8fc4fffc addresses ptr If you observe the whole scenario you will find that directly or indirectly we are getting an array containing 5 members, each of these members having a integer values (int data-type). The base addresses being assigned to the pointer variable ptr itself. Now we are free to apply the pointer arithmetic to the base pointer ptr to read and 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. 8fc4fff6 The third location can be referred as ( ptr + 2) ie. 8fc4fff8 The fourth location can be referred as ( ptr + 3) ie. 8fc4fffa The fourth location can be referred as ( ptr + 4) ie. 8fc4fffc

Page 13: Pointers

Page 13 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Similarly 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 manner you find that we have ultimately created a 1-Dimensional Array having 5 elements 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 infer that the name of base pointer (ptr) in the second version is acting same as the name of the array (arr) itself present in the second version. The above two versions can be used in compliment of each other, as and when required. They can also be used in mixed form. So the following expressions are equivalent : arr[i] Ξ *(arr +i) So , following mixed expressions can be used while writing codes using arrays : main( ) { int MyArray[5] ;

Note : The name of any array declared in any C++ program, is a pointer to the address of the first element of that array.

Page 14: Pointers

Page 14 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

//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 :” ;

Page 15: Pointers

Page 15 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

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.

Page 16: Pointers

Page 16 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Pointer with different operators : Pointer with Assignment operator : We know that we can assign value of a simple variable into another variable by using 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. 90 Similarly 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 other When we write pointer a = b then the address which is being stored in b i,e a Hexadecimal value , gets copied into pointer a removing any of its previous contents (address). Pointer with comparison operator ( ==) Just like we use comparison operator (==) between two simple variables, we can also 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.

Page 17: Pointers

Page 17 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Now 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 with your teacher. Pointers and Strings: We already know that a string is not just a 1-dimensional array of characters but it 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”;

Also we have gathered knowledge that the name of a 1-dimensional array is itself a pointer to the first member of that array. So the above diagram can be more clearly represented as: Memory addresses 8fc4fff4 8fc4fff5 8fc4fff6 8fc4fff7 8fc4fff8 8fc4fff9 * MyName (name of the string)

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.

‘K’ ‘a’ ‘m’ ‘a’ ‘l’ ‘\0’

‘K’ ‘a’ ‘m’ ‘a’ ‘l’ ‘\0’

Page 18: Pointers

Page 18 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

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.

So from above explanation we conclude that the name of a String variable is also acting as a pointer (pointing to the memory address of its first character). If we try to print the name of the String variable with a cout statement then it will print the address of first character in the string. e.g. : the statement cout<<MyName ; will print 8fc4fff4 (or some other address)

Page 19: Pointers

Page 19 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Try 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)<<”\n\t”; } 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 is having a special role to play. One question that might strike in your head that if a pointer is a variable it must also have some memory allocation with a specific memory address (Hexadecimal address). Yes you are perfectly right. Pointers do have their own addresses just like a simple variable.

Page 20: Pointers

Page 20 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Now a million dollar question arises that if pointers do have their own memory addresses, then their might be some variable which must be having ability to store memory address of a pointer. Yes there are special variables which are intended to store the memory addresses of other pointer variables. These special variables are called pointer to a pointer or more precisely Double Pointers. The whole scenario could be explained by following diagram: int a Ordinary Variable value of a address of a 8fc4fff2 int * aa Pointer variable storing address of a value of aa address of pointer aa 9acfff4 int ** aaa Pointer to a pointer variable Declaring Double Pointer variable: A double pointer variable can be declared in the same way as a normal pointer variable 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) =

56

8fc4fff2

9acfff4

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; 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.

Page 21: Pointers

Page 21 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Array 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 find that it is nothing but a 1- D Array of String. Now since we know that a string can be held by a single character pointer, hence to hold five city names we must be supplied with 5 character pointers. More precisely we must be having a 1-D array of pointers to get hold 5 different city names. Following figure will clear the picture : *str 0x4cfff2 *(str +1) *(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 of some or the other characters. Now if we want to hold this whole array of string by using only a single pointer can we do it.

0x4cfff2

0x4cfff9

: :

‘D’ ‘e’ ‘l’ ‘h’ ‘i’

‘\0’

‘K’ ‘o’ ‘l’ ‘k’ ‘a’ ‘t’ ‘a’ ‘\0’

Page 22: Pointers

Page 22 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

Yes of course this can be done, just like you have captured the address of first character of a string into a char pointer, to grab the whole string, you can also use a double pointer to capture the address of first pointer variable of that Array of pointers. So to hold an Array of strings one can use a double pointer using following code snippet: char CityName = { “Delhi”, “Kolkata”, “Mumbai”, “Chennai” }; or char ** CityName = { “Delhi”, “Kolkata”, “Mumbai”, “Chennai” }; Functions and Pointers : Pointers could be passed to functions as parameters just like we pass ordinary variables 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; }

Exercise : Try to write a program which will read and write array of strings from user using the above double pointer notation.

Page 23: Pointers

Page 23 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

//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 because we have called the function IncreaseByTen( ) by passing the address of the variable 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 a function separated by comma. Pointer and Structures: A pointer variable can also hold the address of a structure variable like it holds the 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 structure variable using these pointer variables?

Page 24: Pointers

Page 24 of 24

Prepared By Sumit Kumar Gupta, PGT Computer Science

For this we make use of direction operator (). For example if we want to print the value of the X- Coordinate and Y-Coordinate of structure variable P1 making use of its pointer f then we must write the statement as : cout<< f XCoord << f YCoord ; 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 we can 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 variable which will store the address of the Next term of a Polynomial.

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 << P1XCoord << P1YCoord; 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.