Coupon Accepted Successfully!



A pointer is a variable that holds a memory address, usually the location of another variable in memory. Pointer is a variable, which contains memory address. This address is the location of another variable in memory. Consider 2 variables. If the first variable contains the address of second variable then it is said the first variable points to second variable


1000 1002 1004 1006 1008 1010 1012



In the above picture the variable at 1000 is a pointer to the variable at 1004 Here comes the operator '*'(asterisk). This operator is used to declare a pointer type variable. The declaration of such a variable consists of type (any valid type), '*' and variable name. The syntax for this purpose is as follows


 * ; The type defines here which type of data the pointer is going to point. This means which type of variableas address this pointer will point to. The "&" operator gets the address of any variable and the '*' operator counters the '&' operator. That is gets the value at that address taking into consideration the base type. Let us see an example.   int a, b ; int *ptr1, *ptr2; /*Here ptrl and ptr2 re two pointer type v a r i a b l e s , which can contin the ddress of 2 integer variables*/ ptrl=&a; ptr2=&b;   In the above example ptrl contains the address of a and ptr2 contains the address of b.

By address it is meant the memory location of the variable at the run time. Suppose at run time a is at location 1004 and it has a value of say 50 then ptrl will contain 1004 not 50. Let us now check the * operator. This operator gets the value. So to get the value stored at any location we can write m=*ptrl; Here type of m and base type of ptrl must be same. Now contains the value stored at address pointed by ptrl, that is value of a.

A pointer can be assigned to another pointer type variable of same base type Consider the following code.   int a int *ptr1, *ptr2; ptrl=&a; /* ptr l is assiged the a ddress of a */ ptr2=ptl; /* ptr2 also stores the address of a */ printf(“%p%p”, ptr1, ptr2); /* will p rint address of 2 times */   The above code shows assign ing of the address of a variable in to a pointer type variable. Then we store the address stored in one pointer type variable in another pointer type variable. Then in last statement we are printing the address stored in those pointers. You can notice we are using a %p a here to print the address.

Addition and Subtraction

Addition and subtraction in pointers deal with constants, as 2 pointers cannot be added or subtracted. The obvious question in your mind is why, is not it?? Well think in this way, pointer is an address of a variable. So adding two addresses has no meaning and it wont help in any circumstances. Like if you add your address with your friends address then what will happen? It is now clear I think.

You can add a constant to a pointer the constant is some times known as offset. You can increment or decrement a pointer too. We will see these in detail in pointer and array relationship shortly. But for the time being remember the above restriction.   int *p,*q,*r; r=p+q; //wrong r=p-q; //wrong r=p+1; //right q+=1; //right q++; //right q--; //right ++q; //right --q; //right   An interesting thing to mark here suppose in above example code apa points to 1000, then ap++a points to 1002 not 1001. This is because address if added with a constant gives the address of another variable of same type as that of base type of pointer. Here base type of pointer is ainta, each integer takes 2 bytes adding one means the address of next integer which is 2 bytes away

Relation between Array and Pointer

Pointers are cousins to arrays. They have many things in common and can some times be used interchangeably. The first point to remember here is array name is a pointer. Hence we can apply pointer arithmetic to array. See the picture bellow.   myarray 0 1 2 3 4 5 6 7 8 9 5 8 1 14 25 7 63 14 95 43 100 102 104 106 108 110 112 114 116 118   The addresses are assumed in the above picture. When you create an array the program reserves memory for it. The amount of memory reserved is dependent on the type of each element of array and size of array. In the above case we assumed elements are integer type and the size of array is 10. Thus the corresponding program declaration is like bellow. int myarray[10]; Here our program reserved 20 bytes in consecutive memory location starting at 1000.

From the above picture you can guess the address of 0th element is 1000, address of 1st element is 1002 and so on. Now let us access the elements For this we will use a[ ] a operator. If we print myarray[0] it will print 5, for myarray[l] it will output 9 and so on. Here instead of writing the index directly. Consider the following code   Main() { Int i=0; Int myarray[10]; ………. ………. While(i<10) { Printf(“%d th Element = %d\n ”,i,myarray[i]); Cell value Address i++; }   This will print the array elements. Now we will change some thing in th while loop. Rewrite the while loop as follows. We now know the array name is The address of the first element of array. Hence we will use the value at operator   …….. int *a; a=myarray; while(i<10) { printf(“%d th Element = %d\n”,i,*a); i++; a++; }   See the result, they are same, is not it?

From the above example you could see the pointer assignment, value at address and pointer arithmetic. In the above example instead of writing a-|—|- you can write a+=l too. More of array and pointer relation we will se latter in this chapter. We just see the relation between pointer and single dimensional array. Can there be a pointer to multi dimensional array? Yes, certainly. But incase of multi dimensional array the declaration is a bit different but similar. In case of onedimensional array we put a single * in front of the pointer type variable. In this case we have to put number of stars depending upon the number of dimension. For example, in case of 2-dimensional array **, in three-dimensional array *** and so on. The number of stars should be equal to number of dimensions-   int b[2][3]; int c[2][4][2]; int **k; int ***m; k=b; m=c;  

Array of Pointer

If array of any data type is possible then array of pointers is also possible. In this case each element of the array is a pointer to any data type. Suppose we want to create an array of integer pointer then we should write in following manner.   int k,l,m,n; int *a[4]; /* here a is an array of pointe to integer */ /*hence we cn write*/ a[0]=&k; a[l]=&l a[2]=&m a[3]=&n;  

Multidimensional Array

We read earlier how to represent multi dimensional arrays using pointers. Now we will look into how to access the elements of multi dimensional array. Follow the example bellow. Int a[3][3][3]; /* is a multi d ie ns io n array*/ Int p,x,y,z,; Int ***k; /* k is a pointer to pointe to pointer to integer */ /* hence k can hold the address of 3-diensional array */ k=a; /*now we will store values into the array*/ for(x=0;x<3;x+ +) { fo(y=0;y<3;y++) { for(z=0;z<3;z++) { printf'("Enter e l eme n t %d %d %d\n", x, y, z ); scanf("%d",&p); /* read the element */ *(*(*(k+x)+y)+z)=p; /* store the e l eme n t in array */ } } } /*now to print the vlues */ for(x=0;x<3;x+ +) { for(y=0;y<3;y++) { for(z=0; z<3;z++) { p=*(*(*(k+x)+y)+z); printf ("The El eme n t %d %d %d= %d\n", x, y,z , p); }} }  

Function and pointer

We have discussed pass by value method in functions. In that case the value is passed to the function. But in case of pass by reference we pass the address of variables to the called function. As the address of variable is passed, any modification of value at that address will be reflected in the calling function. Hence this should be considered seriously. The pass by reference is advantageous when we pass array or we need the variableas value should be changed by the function. Consider the case of a swapping function we need to alter the values and that should be available in calling function. We know a function can return only one value hence pass by value is not possible. So it is done using pass by reference. Consider the following swapping example   #include void swap (int *p, int *q) /* we take two pointers */ int * temp /* temporary pointer variable */ *temp= * /*'store the value stored in p*/ *p= *q; /* store v a lu e stored in p into q */ *q= *temp; } main() { int a=10 b=30; printf(“value of a =%d and of b =%d before swap( ) \ n " , a , b ); swap (&a, &b); /* passing addresses*/ printf(“value of a =%d and of b =%d before swap( ) \ n " , a , b ); }  


Array means a group of similar type of things. In C programming it means a collection of similar type of data in consecutive memory locations, as an example array of integers array of floats etc. Types of Arrays Single-dimensional array Multi-dimensional array

Single-dimensional Array

The simplest form of an array is a single dimensional array. The array is given a name and is elements are referred to by their subscripts or indices. Introduction to Array Variables Arrays are a data structure which hold multiple values of the same data type. Arrays are an example of a structured variable in which 1) there are a number of pieces of data contained in the variable name, and 2) there is an ordered method for extracting individual data items from the whole. Consider the case where a programmer needs to keep track of the ID numbers of people within an organization. Her first approach might be to create a specific variable for each user. This might look like int id1 = 101; int id2 = 232; int id3 = 231; It becomes increasingly more difficult to keep track of the IDs as the number of variables increase. Arrays offer a solution to this problem.

Array Variables Example

An array is a multi-element box, a bit like a filing cabinet, and uses an indexing system to find each variable stored within it. In C, indexing starts at zero. Arrays, like other variables in C, must be declared before they can be used. The replacement of the previous example using an array looks like this: int id[3]; /* declaration of array id */ id[0] = 101; id[1] = 232; id[2] = 231; In the first line, we declared an array called id, which has space for three integer variables. Each piece of data in an array is called an element. Thus, array id has three elements. After the first line, each element of id is initialized with an ID number.

Memory Representaion of Single Dimension Arrays

Single –dimension arrays are essentially lists of information of the same type andtheir elements are stored in contiguous memory location in their index order. For instance, an array grade of type char with 8 elements declared as char grade[8]; will have the element grade[0] at the first allocated memory location, grade[1] at the next contiguous memory location, grade[2] at the next, and so forth. Since grade is a char type array, each element size is 1 byte(A character size is 1 byte) and it will be represented in memory as shwn below grade[0] grade[1]……………………………………………………..grade[7] Address 101 102 103 104 105 106 107 108 If you have an int array age with 5 elements declared as int age[5]; Its each element will have sizeof(int)1 bytes for its storage. On a system with 2 bytes integer size, the array age’s each element (being an integer ) will be having 2 bytes for its storage. If the starting memory location of array age is 100, then it will be represented in the memory as shown below age[0] age[1] age[2] age[3] age[4] Address 100 102 104 106 108

Declaring Arrays

Arrays may consist of any of the valid data types. Arrays are declared along with all other variables in the declaration section of the program and the following syntax is used type array_name[n]; grade age where n is the number of elements in the array. Some examples are int final[160]; float distance[66]; During declaration consecutive memory locations are reserved for the array and all its elements. After the declaration, you cannot assume that the elements have been initialized to zero. Random junk is at each element’s memory location.

Initializing Arrays during Declaration

If the declaration of an array is preceded by the word static, then the array can be initialized at declaration. The initial values are enclosed in braces. e.g., static int value[9] = {1,2,3,4,5,6,7,8,9}; static float height[5]={6.0,7.3,2.2,3.6,19.8}; Some rules to remember when initializing during declaration If the list of initial elements is shorter than the number of array elements, the remaining elements are initialized to zero. If a static array is not initialized at declaration manually, its elements are automatically initialized to zero. If a static array is declared without a size specification, its size equals the length of the initialization list. In the following declaration, a has size 5. static int a[]={-6,12,18,2,323};

Using Arrays

Recall that indexing is the method of accessing individual array elements. Thus grade[89] refers to the 90th element of the grades array. A common programming error is out-of-bounds array indexing. Consider the following code: int grade[3]; grade[5] = 78; The result of this mistake is unpredictable and machine and compiler dependent. You could write over important memory locations, for example. Often run-time errors result.
Array variables and for loops often work hand-in-hand since the for loop offers a convenient way to successively access array elements and perform some operation with them. Basically, the for loop counter can do double duty and act as an index for the array, as in the following summation example:   int total=0,i; int grade[4]={93,94,67,78}; for (i=0; i<4; ++i) total += grade[i]; int num[3] = {7, 51, -22}; float values[5] = {2.1, 6.7}; char name[] = {‘F’, ‘r’, ‘e’, ‘d’}; - The first element of the array is index 0. If there are N elements, the last on is index (N-1).    


Example: #include main() { int a[5]; \\A for(int i = 0;i<5;i++) { a[i]=i; \\B } print_elements(a); } void print_elemets(int a[]) { Remaining 3 values get initialized to zeros The compiler fills in the 4 after counting the number of initiallizers. Beware: not a null-terminated string! for(int i = 0;i<5;i++) { printf("value in array %d\n",a[i]); } }  


Explanation Statement A defines an array of integers. The array is of the size 5—that means you can store 5 integers. Array elements are referred to using subscript; the lowest subscript is always 0 and the highest subscript is (size –1). If you refer to an array element by using an out-of-range subscript, you will get an error. You can refer to any element as a[0], a[1], a[2], etc. Generally, you can use a for loop for processing an array. For the array, consecutive memory locations are allocated and the size of each element is same. The array name, for example, a, is a pointer constant, and you can pass the array name to the function and manipulate array elements in the function. An array is always processed element by element. When defining the array, the size should be known.

Test Your Skills Now!
Take a Quiz now
Reviewer Name