Friday 26 November 2010

Pointers


Pointers :
Pointers are another important feature of C Language. Although they may appear a little confusing for a beginner, they are a powerful tool and handy to use once they are mastered. There are a number of reasons for using pointers.
1). A pointer enables us to access a variable that is defined outside the function.
2). Pointers are more efficient in handling the data tables.
3). Pointers reduce the length and complexity of a program.
4). They increase the execution speed.
5). The use of a pointer array to character strings result in saving of data storage
            pace in memory.
[*] Understanding Pointers :
Computers use their memory for storing the instruction of a program, as well as the values of the variables that are associated with it. The computer’s memory is a sequential collection of ‘storage cells as shown in fig as below. Each cell, commonly known as a byte, has a number called address associated with it. Typically the address are numbered are start from zero. The last address depends on the memory size. A computer system having 64K memory will have its last address as 65,535.                                                          


Whenever we declare a variable, the system allocates, somewhere in the memory, an appropriate location to hold the value of the variable. Since, every byte has a unique address number, this location will have its own address number. Consider the following statement :
                        Int quantity = 179;
This statement instruct the system to find a location for the integer variable quantity and puts the value 179 in that location. Let us assume that the system has chosen the address location 5000 for quantity.
   

During the execution of the program, the system always associates the name quantity with the address 5000. we may have access to the value 179 by using either the name quantity or the address 5000. since memory addresses are simply numbers, they can assigned to some variables which can be stored in memory, like any other variable. Such variables that hold memory addresses are called pointer. A pointer is, therefore, nothing but a variable that contains an address which is a location of another variable in memory.
Remember, since a pointer is a variable, its value is also stored in the memory in another location. We assign the address of quantity to a variable p. the link between the variables p and quantity can be visualized in fig.

                                               
The address of p is 5048. Since the value of the variable p is the address of the variable quantity, we may access the value of quantity by using the value of p and therefore, we say that the variable p points to the variable quantity. Thus, the p gets the name ‘Pointer’.

Pointer Expressions :
Pointer variables can be used in expressions. For example, if p1 and p2 are properly declared and initialized pointers, then the following statements are valid.
                        Y = *p1 * *p2;             same as  (*p1) * (*p2)
                        Sum = sum + p1;
                        Z = 5* - *p2/*p1;                    same as  (5 * (-(*p2))) / (*p1)
                        *p2= *p2 + 10;          
            Note that there is a blank space between / and * in the item3 above. The following is wrong.
                        Z = 5* - *p2/*p1;
            The symbol /* is considered as the beginning of a comment and therefore the statement fails.
            We may also use short-hand operators with the pointers.
                        P1++;
                        --P2;
                        Sum += *p2;
Pointer can also be compared using the relational operators. The expressions such as p1 > p2, p1 == p2, and p1 != p2 are allowed. However, any comparison of pointers that refer to separate and unrelated variables makes no sense. Comparisons can be used meaningfully in handing arrays and strings.
            We may not use pointers in division or multiplication. For example, expressions such as,
                        P1 / p2 or p1 * p2 or p1 / 3
are not allowed. Similarly, two pointers can’t be added, that is P1 + P2 is illegal.


            Increment & Scale Factor :
            We have seen that the pointers can be incremented like,
                        P1 = p2 + 2;
                        P1 = p1 + 1;
and so on. Remember, however, an expression like
                        p1++;
will cause the pointer p1 to point to the next value of its type. For example, if p1 is an integer pointer with an initial value, say 2800, then after the operation p1 = p1 + 1. the values of p1 will be 2802, and not 2801. that is, when we increment a pointer, its value is increased by the length of the data type that it points to. This length is called Scale Factor. The length of various data types are as follow :
                        Character      1 byte
                        Integers          2 byte
                        Floats             4 byte
                        Long integer 4 byte
                        Doubles         8 byte
The number of bytes used to store various data type depends on the system and can be found by making use of the sizeof operator. For example, if x is a variable, then sizeof(x) returns the number of bytes needed for the variable.

Pointers & Char. :
We know that a string is an array of charters, terminated with a null character. Like in one-dimensional arrays. We can use a pointer to access the individual characters in a string.
Example :
                        main()
{
                                    char *name="DELHI";
                                    int length;
                                    char *cptr=name;
                                    clrscr();

                                    //name ="DELHI";
                        while((*cptr)!='\0')
                        {
                                    printf("\n%c is stored at address %u\n",*cptr,cptr);
                                    cptr++;
                        }
                        length=cptr-name;
                        printf("\nLenght of the String = %d\n",length);
            A program to count the length of a string.
Char *cptr =name;
Declares cptr as a pointer to a character and assigns the address of the first character of
name as the initial value. Since, a string is always terminated by the null character, the statement
                        While(*cptr != ‘\0’)
Is true untile the end of the string is reached.
When the while loop is terminated, the pointer cptr holds the address of the null character. Therefore, the statement
                        Length = cptr – name;
Gives the length of the string name.
The output also shows the address location of each character. Note that each character occupies one memory cell(byte). In C, a constant character string always represents a pointer to that string and therefore the following statements are valid :
                        Char *name ;
                        Name = “Delhi”;
The statement will declare name as a pointer to character and assign to name the constant character string “Delhi”. You might remember that this type of assignment does not apply to character arrays. The statement like,
                        Char name[20];
                        Name = “Delhi”;
Do not work.
The character arrays with the rows of varying length called ragged arrays and are better
 handled by pointers.


Pointers & Functions :
When an array is passed to a function as an argument, only the address of the first element of
the array is passed, but not the actual values of the array elements. If X is an array, when we call sort(x), the address of x[0] is passed to the function sort. The function uses this address for manipulating the array elements. Similarly, we can pass the address of a variable as an argument to a function in the normal fashion.  When we pass addresses to a function, the parameters receiving the address should be pointers. The process of calling a function using pointers to pass the address of variable is known as call by reference. The function which is called by ‘reference’ can change the value of the variable used in the call. Consider the following code :
                        Main()
                        {
                                    Int x;
                                    X = 20;
                                    Change(&x);
                                    Printf(“%d\n”,x);
                         }
                        Change(p)
                        Int *p;
                        {
                                    *p = *p + 10;
                         }
When the function change() is called, the address of the variable x, not its value, is passed into the function change(). Inside change(), the variable p is declared as a pointer and therefore p is the address of the variable x. the statement,
                                    *p = *p + 10;
Means ‘ add 10 to the value stored at the address p’. since p represent the address of x, the value of x is changed from 20 to 30. therefore, the output of the program will be 30, not 20.
Thus, call by reference provides a mechanism by which the function can change the stored values in the calling function.
            You may note the following points :
1). The function parameters are declared as pointers.
2). The dereference points are used in the function body.
3). When the function is called, the addresses are passed as actual arguments.
            Pointer parameters are commonly employed in string functions. Consider the function copy
            hich copies one string to another.
                        Copy(s1,s2)
                        Char *s1, *s2;
                        {
                                    While((*s1++ = *s2++) != ‘\0’)
                         }
This copies the contents of s2 into the string s1. parameters s1 and s2 are the pointers
to character strings, whose initial values are passed from the calling function. For example,
the calling statement,
                        Copy(name1,name2);
Will assign the address of the first element of name1 to s1 and the address of the first element of name2 to s2.
Each character, after it has been copied, is compared with ‘\0’ and therefore
copying is terminated as soon as the ‘\0’ is copied.





           Pointers & Structure :
            We know that the name of an array stands for the address of its zeroth element. The same thing is true of the names of arrays of structure variables. Suppose product represents the address of its zeroth element. Consider the following declaration :

                        Struct inventory
                        {
                                    Char name[30];
                                    Int number;
                                    Float price;
                         }
                        Product[2], *ptr;
This statement declares product as an array of two elements, each of the type struct inventory and ptr as a pointer to data objects of the type inventory. The assignment,
                        Ptr = product;
Would assign the address of the zeroth element of product to ptr. That is, the pointer ptr will now point to product[0]. Its members can be accessed using the following notation.
                        Ptr à name
                        Ptr à number
                        Ptr à price
            The symbol à is called the arrow operator is made up of a sign and a greater than sign. Note
that ptr à is simply another way of writing product[0]. When the pointer ptr is incremented by one, it is made to point to the next record. i.e. product[1].

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Grants For Single Moms