Pointers

24
Page 1 of 24 Prepared By Nishant Tiwari, 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

cplus

Transcript of Pointers

  • Page 1 of 24

    Prepared By Nishant Tiwari, 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

    #includemain( )

    {

    char points[ ] = We are KVians

    while(points[i] != /0) {

    cout

  • Page 2 of 24

    Prepared By Nishant Tiwari, 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.

    3 2

  • Page 3 of 24

    Prepared By Nishant Tiwari, 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 cant

    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

    *

    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 of 24

    Prepared By Nishant Tiwari, 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

    0 x8fbffff4 &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

    0 x8fbffff4

  • Page 5 of 24

    Prepared By Nishant Tiwari, 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

  • Page 6 of 24

    Prepared By Nishant Tiwari, 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

  • Page 7 of 24

    Prepared By Nishant Tiwari, PGT Computer Science

    {

    int a , *ptr ;a = 30 ;

    ptr = &a;

    cout

  • Page 8 of 24

    Prepared By Nishant Tiwari, 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.

    Lets understand the concept by running the following code snippet:

    main()

    {

    int *MyArray; // Line 1 :int size ;

    cout> size; // Line 4

    MyArray = new int[size]; // Line 5 : initializing pointer MyArray with an address.

    for(int i = 0 ; i

  • Page 9 of 24

    Prepared By Nishant Tiwari, 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 * s ize * 2 bytes in memory, and all these bytes would be reserved till you

    restart your machine. This reserved memory cant 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 = ;

    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 of 24

    Prepared By Nishant Tiwari, 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 cant write following statement after we

    have declared MyVar as const :

    MyVar = 23; // InvalidOr 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 = &;

    More precisely :

    int a = 20 , b = 30 ;

    const int * MyConstPointer = &a;

    After we have declared a const pointer, we cant 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 ! cant 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

  • Page 11 of 24

    Prepared By Nishant Tiwari, 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

  • Page 12 of 24

    Prepared By Nishant Tiwari, PGT Computer Science

    main ( )

    { const int * ptr ;

    int a = 80 ;

    ptr = &a ;

    a += 3;cout

  • Page 13 of 24

    Prepared By Nishant Tiwari, PGT Computer Science

    Similarly to read and write value at these locations we can readily use (*)

    operator i,e.

    *p tr 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 lets 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 *(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 of 24

    Prepared By Nishant Tiwari, PGT Computer Science

    //Inputting array elements

    for(int i = 0 ; i MyArray[i]; // Using array notation

    }

    // Showing array elements

    for( i = 0 ; i

  • Page 15 of 24

    Prepared By Nishant Tiwari, PGT Computer Science

    cin>> *(arr + i) ;

    } for(i = 0 ; i

  • Page 16 of 24

    Prepared By Nishant Tiwari, 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

  • Page 17 of 24

    Prepared By Nishant Tiwari, 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

  • Page 18 of 24

    Prepared By Nishant Tiwari, 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 dont 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

  • Page 19 of 24

    Prepared By Nishant Tiwari, PGT Computer Science

    Try to find the error or output:

    #include

    main( )

    {

    char * MyName = Kamal Kant Gupta; int i = 0;

    while( I

  • Page 20 of 24

    Prepared By Nishant Tiwari, 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 tostore 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 8 fc4fff2 int * aa Pointer variable storing address

    of a

    value of aa

    address of pointer aa 9 acfff4 int ** aaa Pointer to

    a pointervariable

    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)

    =

    5 6

    8 fc4fff2

    9 acfff4

    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 cant assign simple pointer to a double pointer int **s = &p; int **f = s // Correct can assign double pointer to another double pointer.

  • Page 21 of 24

    Prepared By Nishant Tiwari, 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

    0 x4cfff2 * (str +1)

    * (str +2) 0 x4cfff9

    * (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.

    0 x4cff f2

    0 x4cff f9

    :

    :

    D e l h i \0

    K o l k a t a \0

  • Page 22 of 24

    Prepared By Nishant Tiwari, PGT Computer Science

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

    Lets understand how to pass pointers to a function by an example code:

    main( )

    {

    int x = 70 ;

    cout

  • Page 23 of 24

    Prepared By Nishant Tiwari, PGT Computer Science

    //function IncreaseByTen

    void IncreaseByTen(int *ptr )

    {

    *p tr += 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 of 24

    Prepared By Nishant Tiwari, 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